Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Getting Started with Solon: A Lightweight Alternative to Spring Boot

Notes May 17 2

Solon is designed as a lightweight, high-performance application framework offering significant improvements in startup time, concurrency handling, and resource consumption compared to established alternatives. It supports various Java runtimes from Java 8 up to the latest LTS versions.

Core Concept Mappings

Developers transitioning from standard enterprise frameworks can adapt quickly due to direct conceptual parallels. Key annotations provide streamlined functionality:

  • Dependency Injection utilizes @Inject exclusively, removing verbose boilerplate.
  • Web endpoints combine controller and response beahviors under @Controller.
  • Path mappings rely on @Mapping instead of complex path strategies.
  • Service layers do not require specific stereotypes; @Component suffices.

Web Controller Implementation

import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Inject;

@Controller
@Mapping("/accounts")
public class AccountController {

    @Inject
    private AccountService accountLogic;

    @Get
    @Mapping("/status")
    public UserProfile getProfile() {
        Long userId = SecuritySession.getId();
        return accountLogic.fetchById(userId);
    }

    @Get
    @Mapping("/records")
    public List<AccountItem> listRecords() {
        return accountLogic.findAll();
    }
}

Service Layer Composition

Business logic remains consistent with standard patterns. Using @Component ensures automatic registration without intermediate abstraction interfaces where possible.

import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

@Component
public class AccountServiceImpl implements AccountService {

    @Inject
    private DepartmentService departmentHelper;

    @Override
    public void updateDetails(UserData data) {
        // Processing logic here
    }
}

Configuration Binding

External settings are bound automatically. Using @Inject with property keys achieves what standard configuration properties classes offer, reducing XML or YAML complexity.

import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Inject;
import lombok.Data;

@Data
@Configuration
@Inject("${app.server.config}")
public class ServerSettings {

    private String basePath;
    private int maxUploadSize;
}

In application.yml:

app:
  server:
    config:
      basePath: "/var/www"
      maxUploadSize: 500000000

Context Management and HTTP Clients

Accessing request context allows retrieving headers or parameters seamlessly.

import org.noear.solon.Context;

public String extractToken(Context ctx) {
    String tokenHeader = ctx.header("Authorization");
    String tokenParam = ctx.param("token_id");

    if (tokenHeader != null && !tokenHeader.isEmpty()) {
        return tokenHeader;
    }
    return tokenParam;
}

Outbound requests benefit from built-in utilities, avoiding external library overhead.

import org.noear.solon.net.HttpClient;

public String callRemote(String targetUrl, Object payload) {
    try {
        String jsonBody = JSONUtil.toJsonString(payload);
        return HttpClient.create(targetUrl)
                .body(jsonBody)
                .header("Content-Type", "application/json")
                .post()
                .getBody();
    } catch (Exception e) {
        throw new SystemException("Communication Failed", e);
    }
}

Application Entry Point

Bootstrapping requires a single main class ennotated with @SolonMain. Filters and cross-origin policies are applied during initialization.

import org.noear.solon.Solon;
import org.noear.solon.annotation.SolonMain;

@SolonMain
public class Application {
    public static void main(String[] args) {
        Solon.start(Application.class, args, app -> {
            app.filter(-1, ctx -> {
                // Global CORS filtering logic
            });
        });
    }
}

Tooling support extends to community editions of popular IDEs, ensuring acessibility without licensing restrictions typical of enterprise tools. Ecosystem plugins continue to mature rapidly to cover diverse integration scenarios.

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.