### Configuration Example Source: https://solon.noear.org/article/1404?format=md Example configuration for AI models in config.yml. ```yaml soloncode: models: - apiUrl: "https://api.deepseek.com/v1/chat/completions" apiKey: "sk-xxxxxx" model: "deepseek-chat" timeout: "180s" ``` -------------------------------- ### Hello World Controller Example Source: https://solon.noear.org/article/learn-quickstart Java code for a simple Solon controller that handles a '/hello' endpoint. ```java package com.example.demo; import org.noear.solon.annotation.Controller; import org.noear.solon.annotation.Mapping; import org.noear.solon.annotation.Param; @Controller public class DemoController { @Mapping("/hello") public String hello(@Param(defaultValue = "world") String name) { return String.format("Hello %s!", name); } } ``` -------------------------------- ### Solon Example Source: https://solon.noear.org/article/642 A basic example demonstrating how to start the Solon application using both manual and annotation modes. ```java @Controller public class App { public static void main(String[] args) { Solon.start(App.class, args, app -> { //手写模式 app.router().get("/hello1", ctx -> ctx.output("Hello world!")); }); } //注解模式 @Get @Socket @Mapping("/hello2") public String hello2(String name) { return String.format("Hello %s!", name); } } ``` -------------------------------- ### Flow Definition Example Source: https://solon.noear.org/article/898?format=md Example of a flow definition in YAML format. ```yaml id: "c1" layout: - { id: "n1", type: "start", link: "n2"} - { id: "n2", type: "activity", link: "n3", task: "System.out.println(\"hello world!\");"} - { id: "n3", type: "end"} ``` -------------------------------- ### Start Coding Source: https://solon.noear.org/article/728 Example demonstrating how to start a Solon application and implement both classic and reactive controllers. ```java public class DemoApp { public static void main(String[] args){ Solon.start(DemoApp.class, args); } } @Controller public class DemoController { //经典的 @Mapping("/hi") public String hi(String name) { return "Hello " + name; } //响应式的 @Mapping("/hello") public Mono hello(String name) { return Mono.fromSupplier(() -> { return "Hello " + name; }); } } ``` -------------------------------- ### Application Configuration Source: https://solon.noear.org/article/898?format=md Configure Solon Flow to load flow definitions from classpath. ```yaml solon.flow: - "classpath:flow/*.yml" ``` -------------------------------- ### Example AI Model Configuration Source: https://solon.noear.org/article/1404 An example configuration for AI models in the `config.yml` file, showing settings for DeepSeek. ```yaml soloncode: models: - apiUrl: "https://api.deepseek.com/v1/chat/completions" apiKey: "sk-xxxxxx" model: "deepseek-chat" timeout: "180s" ``` -------------------------------- ### SolonProps Configuration Example Source: https://solon.noear.org/api/org/noear/solon/package-summary.html Demonstrates how to manually get configuration values using Solon.cfg() and access properties like debug mode, drift mode, and specific configurations like 'water.logger' and 'db1'. It also explains the priority of configuration sources. ```java // 手动获取配置模式(容器自动模式可用: @Inject("${water.logger}")) // 配置的优先级:命令参数-> 环境配置-> 系统配置-> 应用配置 (越动态的越优化) Solon.cfg() Solon.cfg().isDebugMode() Solon.cfg().isDriftMode() Solon.cfg().get("water.logger") Solon.cfg().getProp("db1") ``` -------------------------------- ### Example 1: Simple Flow (demo1.yml) Source: https://solon.noear.org/article/899 A basic example demonstrating the structure of a flow graph with start, activity, and end nodes. ```yaml id: "d1" layout: - { id: "s", type: "start", link: "n1"} - { id: "n1", type: "activity", link: "e", task: "System.out.println(\"hello world!\");"} - { id: "e", type: "end"} ``` -------------------------------- ### HelloworldController Example Source: https://solon.noear.org/article/251?format=md An example Java controller demonstrating how to inject configuration, handle requests, and return a ModelAndView for a JSP view. ```java @Controller public class HelloworldController { //这里注入个配置 @Inject("${custom.user}") protected String user; @Mapping("/helloworld") public ModelAndView helloworld(Context ctx){ UserModel m = new UserModel(); m.setId(10); m.setName("刘之西东"); m.setSex(1); ModelAndView vm = new ModelAndView("helloworld.jsp"); //如果是ftl模板,把后缀改为:.ftl 即可 vm.put("title","demo"); vm.put("message","hello world!"); vm.put("m",m); vm.put("user", user); vm.put("ctx",ctx); return vm; } } ``` -------------------------------- ### Example of applying system configuration Source: https://solon.noear.org/article/176?format=md Shows how to set Solon's environment using system properties. ```bash java -Dsolon.env=dev -jar demo.jar ``` -------------------------------- ### Example of applying startup parameters Source: https://solon.noear.org/article/176?format=md Demonstrates how to use command-line arguments to set startup parameters for a Solon application. ```bash java -jar demo.jar --env=dev --drift=1 ``` -------------------------------- ### Hello World Examples Source: https://solon.noear.org/article/24 Demonstrates 'Hello World' implementations using Handler, Controller, and Remoting modes in Solon. ```java @SolonMain public class App{ public static void main(String[] args){ Solon.start(App.class, args, app->{ //Handler 模式: app.router().get("/hello", (c)->c.output("Hello world!")); }); } } //Controller 模式:(mvc or rest-api) @Controller public class DemoController{ //限定 put 方法类型 @Put @Mapping("/mvc/hello") public String hello(String name){ return "Hello " + name; } } //Remoting 模式:(rpc) @Mapping("/rpc/hello") @Remoting public class HelloServiceImpl implements HelloService{ @Override public String hello(){ return "Hello world!"; } } ``` -------------------------------- ### start node example Source: https://solon.noear.org/article/903 Example of a start node in a flow. ```yaml id: demo1 layout: - type: start - type: end ``` -------------------------------- ### Dynamic Configuration - Startup Parameters Source: https://solon.noear.org/article/301 Example of setting configuration values using startup parameters. ```bash java -jar demo.jar -debug=1 ``` -------------------------------- ### Configuration Example Source: https://solon.noear.org/article/150 Configuration example for Solon's aliyun oss file storage. ```yaml solon.cloud.aliyun.oss.file: bucket: world-data-dev endpoint: oss-cn-xxx.aliyuncs.com accessKey: iWeU7cOoPLRokg2Hdat0jGQC secretKey: ZZIH6mT4VLAy68mVP80F7LiB5SpSEM7N ``` -------------------------------- ### SolonCode Installation Directory Structure Source: https://solon.noear.org/article/1404?format=md The file structure of the SolonCode installation directory. ```bash ~/.soloncode/ +-- AGENTS.md # 智能体定义(升级时保留) +-- config.yml # 配置文件(升级时保留) +-- bin/ # 可执行文件目录 | +-- soloncode-cli.jar # 核心程序 | +-- soloncode # Linux/macOS 启动脚本 | +-- soloncode.ps1 # PowerShell 启动脚本 | +-- uninstall.sh # Linux/macOS 卸载脚本 | +-- uninstall.ps1 # PowerShell 卸载脚本 +-- skills/ # 全局技能目录 ``` -------------------------------- ### Run Packaged Application Command Source: https://solon.noear.org/article/learn-quickstart Command to run the packaged Solon application. ```bash java -jar demo.jar ``` -------------------------------- ### Server Application Start Source: https://solon.noear.org/article/892 Example of how to start the Solon server application. ```java public class ServerApp { public static void main(String[] args) { Solon.start(ServerApp.class, args); } } ``` -------------------------------- ### Plugin Hotplug Example Source: https://solon.noear.org/article/263?format=md Demonstrates how to implement the `start` and `stop` methods for a plugin, including adding configurations, scanning beans, registering static repositories, and crucially, removing resources like routes, jobs, event subscriptions, and static repositories during the stop phase to enable hot updates. ```java public class Plugin1Impl implements Plugin { AppContext context; StaticRepository staticRepository; @Override public void start(AppContext context) { this.context = context; //添加自己的配置文件 context.cfg().loadAdd("demo1011.plugin1.yml"); //扫描自己的bean context.beanScan(Plugin1Impl.class); //添加自己的静态文件仓库(注册classloader) staticRepository = new ClassPathStaticRepository(context.getClassLoader(), "plugin1_static"); StaticMappings.add("/html/", staticRepository); } @Override public void stop() throws Throwable { //移除http处理。//用前缀,方便移除 Solon.app().router().remove("/user"); //移除定时任务(如果有定时任务,选支持手动移除的方案) JobManager.getInstance().jobRemove("job1"); //移除事件订阅 context.beanForeach(bw -> { if (bw.raw() instanceof EventListener) { EventBus.unsubscribe(bw.raw()); } }); //移除静态文件仓库 StaticMappings.remove(staticRepository); } } ``` -------------------------------- ### Get MapperFacade Instance Source: https://solon.noear.org/article/487 Example of how to get a MapperFacade instance. ```java @Component public class TestService { @Inject private MapperFacade mapperFacade; } ``` -------------------------------- ### Configuration Example 1 Source: https://solon.noear.org/article/526 Basic configuration example for solon.cloud.etcd. ```yaml solon.app: name: "demoapp" group: "demo" solon.cloud.etcd: server: "localhost:2379" #etcd 服务地址 config: load: "demoapp.yml" #加载配置到应用属性(多个以","隔开) ``` -------------------------------- ### Get MapperFactory Instance Source: https://solon.noear.org/article/487 Example of how to get a MapperFactory instance. ```java @Component public class TestService { @Inject private MapperFactory mapperFactory; } ``` -------------------------------- ### Online Installation Commands Source: https://solon.noear.org/article/1404?format=md Commands for installing SolonCode online on macOS, Linux, and Windows. ```bash # Mac / Linux: curl -fsSL https://solon.noear.org/soloncode/setup.sh | bash ``` ```powershell # Windows (PowerShell): irm https://solon.noear.org/soloncode/setup.ps1 | iex ``` -------------------------------- ### Solon Helloworld Example Source: https://solon.noear.org/article/compare-springboot?format=md A simple Helloworld example demonstrating Solon's Context and Handler architecture, providing a similar experience to Spring Boot. ```java @SolonMain public class App{ public static void main(String[] args){ Solon.start(App.class, args); } } @Controller public class Demo{ @Inject("${app.name}") String appName; @Mapping("/") public Object home(String name){ return appName + ": Hello " + name; } } ``` -------------------------------- ### Plugin Management Example Source: https://solon.noear.org/article/273 Example of managing plugins (load, start, stop, unload) via code. ```java //PluginManager.load("add2"); //加载插件 //PluginManager.start("add2"); //启动插件(未加载的话,自动加载) //PluginManager.stop("add2"); //停止插件 //PluginManager.unload("add2"); //卸载插件(未停止的话,自动停止) public class App { public static void main(String[] args) { Solon.start(App.class, args, app -> { //启动插件 app.router().get("start", ctx -> { PluginManager.start("add1"); ctx.output("OK"); }); //停止插件 app.router().get("stop", ctx -> { PluginManager.stop("add1"); ctx.output("OK"); }); }); } } ``` -------------------------------- ### Add Dependencies Source: https://solon.noear.org/article/723?format=md Dependencies required for the Helloworld example. ```xml org.noear nami-coder-snack3 org.noear nami-channel-http ``` -------------------------------- ### Application Example - Subscription Source: https://solon.noear.org/article/596 Example of subscribing to cloud events. ```java //订阅 @CloudEvent(topic="hello/demo2", group = "test") public class EVENT_hello_demo2 implements CloudEventHandler { @Override public boolean handle(Event event) throws Throwable { System.out.println(LocalDateTime.now() + ONode.stringify(event)); return true; } } ``` -------------------------------- ### WebInput Component Example Source: https://solon.noear.org/article/1059?format=md Example of using the WebInput component to get parameters from a web request. ```yaml - task: @WebInput ``` ```yaml - task: | import org.noear.solon.core.handle.Context; context.put("messsage", Context.current().param("message")); context.put("attachment", Context.current().file("attachment")); ``` -------------------------------- ### Code Example: Initializing and Running the Agent Source: https://solon.noear.org/article/1436 This Java code snippet shows how to initialize the Solon HarnessEngine, configure tool permissions (codesearch, websearch, webfetch), set up an agent session provider, and then prompt the agent with a question about Solon AI annotations. ```java public class DemoApp { public static void main(String[] arg) throws Throwable { //--- 1. 初始化 HarnessProperties harnessProps = new HarnessProperties(".tmp/"); harnessProps.addTools(ToolPermission.TOOL_CODESEARCH, ToolPermission.TOOL_WEBSEARCH, ToolPermission.TOOL_WEBFETCH); //设定工具权限 harnessProps.addModel( null); //设定大模型配置 AgentSessionProvider sessionProvider = new AgentSessionProvider() { private Map sessionMap = new ConcurrentHashMap<>(); @Override public AgentSession getSession(String instanceId) { return sessionMap.computeIfAbsent(instanceId, k -> InMemoryAgentSession.of(k)); } }; HarnessEngine engine = HarnessEngine.of(harnessProps) .sessionProvider(sessionProvider) .build(); engine.prompt("solon ai 有哪些常用的注解?").call(); } } ``` -------------------------------- ### GET Request (Bean) Source: https://solon.noear.org/article/770 Example of making a GET request and deserializing the response body into a Java Bean. ```java Book book = HttpUtils.http("http://localhost:8080/book?bookId=1") .getAs(Book.class); ``` -------------------------------- ### GET Request for Bean Source: https://solon.noear.org/article/770?format=md Example of making a GET request and retrieving the body as a specific Bean type. ```java //for Bean Book book = HttpUtils.http("http://localhost:8080/book?bookId=1") .getAs(Book.class); ``` -------------------------------- ### Application Example - Publishing Source: https://solon.noear.org/article/596 Example of publishing cloud events. ```java //发布(找个地方安放一下) Event event = new Event("hello/demo2", msg).group("test"); return CloudClient.event().publish(event); ``` -------------------------------- ### GET Request (String Body) Source: https://solon.noear.org/article/770 Example of making a GET request and retrieving the response body as a String. ```java String body = HttpUtils.http("http://localhost:8080/hello").get(); ``` -------------------------------- ### Configuration Example Source: https://solon.noear.org/article/153 Configuration example for Solon's cloud MinIO file storage. ```yaml solon.cloud.minio.file: endpoint: 'https://play.min.io' regionId: 'us-west-1' bucket: 'asiatrip' accessKey: 'Q3AM3UQ867SPQQA43P2F' secretKey: 'zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG' ``` -------------------------------- ### Write Code Source: https://solon.noear.org/article/723?format=md Java code for the Helloworld example, demonstrating interaction with the GitHub API. ```java public class MainTest { public static void main(String... args) { GitHub github = Nami.builder() .decoder(new SnackDecoder()) .channel(new HttpChannel()) .upstream(() -> "https://api.github.com") .create(GitHub.class); // Fetch and print a list of the contributors to this library. List contributors = github.contributors("OpenFeign", "feign"); for (Contributor contributor : contributors) { System.out.println(contributor.login + " (" + contributor.contributions + ")"); } } } public interface GitHub { @NamiMapping("GET /repos/{owner}/{repo}/contributors") List contributors(String owner, String repo); @NamiMapping("POST /repos/{owner}/{repo}/issues") void createIssue(Issue issue, String owner, String repo); } public class Contributor { public String login; public int contributions; } public class Issue { public String title; public String body; public List assignees; public int milestone; public List labels; } ``` -------------------------------- ### get Method (Expression and AddStarts) Source: https://solon.noear.org/api/org/noear/solon/core/util/PathMatcher.html Gets a PathMatcher instance for a given expression with an option to add starts. ```java public static PathMatcher get(java.lang.String expr, boolean addStarts) ``` -------------------------------- ### Configuration Example Source: https://solon.noear.org/article/366 Configuration example for Solon cloud aliyun ons. ```yaml solon.app: group: demo #配置服务使用的默认组 name: helloproducer #发现服务使用的应用名 solon.cloud.aliyun.ons: server: http://MQ_IN**************.mq.cn-qingdao.aliyuncs.com:80 #TCP地址 accessKey: LTAI5t6tC2********** secretKey: MLaRt1yTRdfzt2*********** ``` -------------------------------- ### Client Application Example Source: https://solon.noear.org/article/168 Example of how to start a Solon container and use SocketdProxy to call a remote RPC service. ```java //启动客户端 public class ClientApp { public static void main(String[] args) throws Throwable { //启动Solon容器(Socket.D bean&plugin 由solon容器管理) Solon.start(ClientApp.class, args); //[客户端] 调用 [服务端] 的 rpc // HelloService rpc = SocketdProxy.create("sd:tcp://localhost:28080", HelloService.class); System.out.println("RPC result: " + rpc.hello("noear")); } } ``` -------------------------------- ### Get Cleaned Content Example Source: https://solon.noear.org/article/1339 Example of how to get the cleaned content from a ChatResponse, automatically handling the thinking process and printing only the result. It also shows how to access and print the total cost tokens. ```java ChatResponse resp = chatModel.call(prompt); // 自动处理思考过程,只打印结果 System.out.println("Result: " + resp.getResultContent()); // 打印计费信息 AiUsage usage = resp.getUsage(); if (usage != null) { System.out.println("Cost Tokens: " + usage.totalTokens()); } ``` -------------------------------- ### Get cleaned content Source: https://solon.noear.org/article/1339?format=md Example of how to get the cleaned result content and print billing information. ```java ChatResponse resp = chatModel.call(prompt); // 自动处理思考过程,只打印结果 System.out.println("Result: " + resp.getResultContent()); // 打印计费信息 AiUsage usage = resp.getUsage(); if (usage != null) { System.out.println("Cost Tokens: " + usage.totalTokens()); } ``` -------------------------------- ### Application File Placement Example Source: https://solon.noear.org/article/312 This example demonstrates the recommended file and directory structure for managing multiple services, with each service having its own directory and a .jar file. ```shell /jctl.sh #假定脚本放在根目录 /data/sss/waterapi/waterapi.jar /data/sss/waterapi/waterapi_ext/_db.yml /data/sss/waterapi/waterapi_ext/_ext.js.jar /data/sss/wateradmin/wateradmin.jar /data/sss/watersev/watersev.jar /data/sss/waterpaas/waterpaas.jar ``` -------------------------------- ### Quick Verification Commands Source: https://solon.noear.org/article/1404?format=md Commands to verify the installation by running SolonCode in interactive or web mode. ```bash soloncode # cli 交互 或者 soloncode web 0 # web 交互 ``` -------------------------------- ### Application Example Source: https://solon.noear.org/article/150 Example of using CloudClient to upload and retrieve files. ```java public class DemoApp { public void main(String[] args) { SolonApp app = Solon.start(DemoApp.class, args); String key = "test/" + Utils.guid(); String val = "Hello world!"; //上传媒体 Result rst = CloudClient.file().put(key, new Media(val)); //获取媒体,并转为字符串 String val2 = CloudClient.file().get(key).bodyAsString(); } } ``` -------------------------------- ### test2 Source: https://solon.noear.org/api/webapp/demo2_mvc/Param4Controller.html Example of a GET request with a Context parameter. ```java @Get @Mapping(value="test2") public java.util.Map test2(Context ctx) throws java.io.IOException ``` -------------------------------- ### Configuration Example 2 Source: https://solon.noear.org/article/526 More comprehensive configuration example for solon.cloud.etcd, including app metadata and tags. ```yaml solon.app: name: "demoapp" group: "demo" meta: #添加应用元信息(可选) version: "v1.0.2" author: "noear" tags: "aaa,bbb,ccc" #添加应用标签(可选) solon.cloud.etcd: server: "localhost:2379" #etcd 服务地址 config: load: "demoapp.yml" #加载配置到应用属性(多个以","隔开) ``` -------------------------------- ### Host Code Subscription Example (Java) Source: https://solon.noear.org/article/1002?format=md Example of subscribing to topics within the host code before starting the flow. ```Java public class DemoTest { @Test public void case1() throws Exception { FlowEngine flowEngine = FlowEngine.newInstance(); flowEngine.load("classpath:flow/*.yml"); FlowContext context = FlowContext.of(); //事件监听(即订阅) context.eventBus().listen("send.topic1", (event) -> { //for send System.err.println(event.getPayload()); }); //事件监听(即订阅) context.eventBus().listen("call.topic1", (event, data, sink) -> { //for call System.out.println(data); sink.complete("ok"); //答复 }); flowEngine.eval("f1", context); } } ``` -------------------------------- ### Helloworld Example with ReActAgent Source: https://solon.noear.org/article/1281?format=md A Helloworld example demonstrating the use of ReActAgent with Qwen3-32B model and web search tools to answer a complex query. ```java import org.noear.solon.ai.agent.react.ReActAgent; import org.noear.solon.ai.agent.simple.SimpleAgent; import org.noear.solon.ai.annotation.ToolMapping; import org.noear.solon.ai.chat.ChatModel; import org.noear.solon.ai.chat.tool.MethodToolProvider; import java.time.LocalDateTime; public class DemoApp { public static void main(String[] args) throws Throwable { ChatModel chatModel = ChatModel.of("https://api.moark.com/v1/chat/completions") .apiKey("***") .model("Qwen3-32B") .build(); ReActAgent robot = ReActAgent.of(chatModel) .defaultToolAdd(new WebSearchTools()) .build(); String answer = robot.prompt("帮我查一下今年诺贝尔经济学奖得主的最新公开演讲,然后告诉我他演讲中提到的那个中国经济学家(关于债务问题)的主要观点是什么,最后用中文总结一下。") .call() .getContent(); System.out.println("Robot 答复: " + answer); } public static class WebSearchTools { WebSearchRepository webSearchRepository = getWebSearchRepository(); @ToolMapping(name = "search", description = "Search the web for the given query.") public String search(@Param(description = "The query to search for.") String query) throws Throwable { List documentList = webSearchRepository.search(query); return ONode.serialize(documentList); } } } ``` -------------------------------- ### Application Example - Subscribe and Publish Source: https://solon.noear.org/article/156?format=md Java example demonstrating how to subscribe to and publish events using CloudEventService. ```java //订阅 @CloudEvent(topic="hello/demo2", group = "test") public class EVENT_hello_demo2 implements CloudEventHandler { @Override public boolean handle(Event event) throws Throwable { System.out.println(LocalDateTime.now() + ONode.stringify(event)); return true; } } //发布(找个地方安放一下) Event event = new Event("hello/demo2", msg).group("test"); return CloudClient.event().publish(event); ``` -------------------------------- ### Adding a GET Route Source: https://solon.noear.org/article/420?format=md An example of configuring a GET route within the Solon application's initialization lambda. ```java import org.noear.solon.Solon; import org.noear.solon.annotation.SolonMain; @SolonMain public class DemoApp{ public static void main(String[] args){ Solon.start(DemoApp.class, args, app->{ app.router().get("/hello", ctx->{ ctx.output("hello world!"); }); }); } } ``` -------------------------------- ### get Method (expr, addStarts) Source: https://solon.noear.org/api/org/noear/solon/core/util/PathAnalyzer.html Deprecated method to get a PathAnalyzer instance with an expression and a flag for adding starts. ```java public static PathAnalyzer get(java.lang.String expr, boolean addStarts) ``` -------------------------------- ### Hello World Code Example Source: https://solon.noear.org/article/723 A Java code example demonstrating how to use nami to interact with the GitHub API, including interface definitions and data classes. ```java public class MainTest { public static void main(String... args) { GitHub github = Nami.builder() .decoder(new SnackDecoder()) .channel(new HttpChannel()) .upstream(() -> "https://api.github.com") .create(GitHub.class); // Fetch and print a list of the contributors to this library. List contributors = github.contributors("OpenFeign", "feign"); for (Contributor contributor : contributors) { System.out.println(contributor.login + " (" + contributor.contributions + ")"); } } } public interface GitHub { @NamiMapping("GET /repos/{owner}/{repo}/contributors") List contributors(String owner, String repo); @NamiMapping("POST /repos/{owner}/{repo}/issues") void createIssue(Issue issue, String owner, String repo); } public class Contributor { public String login; public int contributions; } public class Issue { public String title; public String body; public List assignees; public int milestone; public List labels; } ``` -------------------------------- ### Equivalence of server port configuration Source: https://solon.noear.org/article/176?format=md Demonstrates two equivalent ways to set the server port configuration. ```bash java -Dserver.port=8081 -jar demo.jar ``` ```bash java -jar demo.jar --server.port=8081 ``` -------------------------------- ### Plugin Code Example Source: https://solon.noear.org/article/273?format=md Example of a plugin implementing the Plugin interface, including resource management during start and stop phases. ```java public class Plugin1Impl implements Plugin { AppContext context; StaticRepository staticRepository; @Override public void start(AppContext context) { this.context = context; //扫描自己的组件 this.context.beanScan(Plugin1Impl.class); //添加自己的静态文件 staticRepository = new ClassPathStaticRepository(context.getClassLoader(), "plugin1_static"); StaticMappings.add("/", staticRepository); } @Override public void stop() throws Throwable { //移除http处理。//用前缀,方便移除 Solon.app().router().remove("/user"); //移除定时任务 JobManager.remove("job1"); //移除事件订阅 context.beanForeach(bw -> { if (bw.raw() instanceof EventListener) { EventBus.unsubscribe(bw.raw()); } }); //移除静态文件仓库 StaticMappings.remove(staticRepository); } } ``` -------------------------------- ### Hello World Example Source: https://solon.noear.org/article/1042 A simple Java example demonstrating the use of SnEL.eval to print 'hello world!'. ```java public class Demo { public satic void main(String[] args) { System.out.println(SnEL.eval("'hello world!'")); } } ``` -------------------------------- ### Basic Configuration Example Source: https://solon.noear.org/article/154 Basic configuration example for Solon Cloud RabbitMQ. ```yaml solon.app: group: demo #配置服务使用的默认组 name: helloproducer #发现服务使用的应用名 solon.cloud.rabbitmq: server: localhost:5672 #rabbitmq 服务地址 username: root #rabbitmq 链接账号 password: 123456 #rabbitmq 链接密码 ``` -------------------------------- ### Starting Solon application with arguments using @SolonTest Source: https://solon.noear.org/article/323?format=md This example demonstrates how to start a Solon application with specific command-line arguments for testing. ```java import org.junit.jupiter.api.Test; @SolonTest(value=webapp.TestApp.class, args="--server.port=9001") public class DemoTest extends HttpTester{ @Inject UserService userService; @Test public void hello() { //测试注入的Service assert userService.hello("world").equals("hello world"); } } ``` -------------------------------- ### Web Example Source: https://solon.noear.org/article/1135 Basic web application setup with a controller. ```java public class DemoApp { public static void main(String[] args) { Solon.start(DemoApp.class, args, app->{ //开始调试模式 //app.onEvent(HttpServerConfigure.class, e->{ // e.enableDebug(Solon.cfg().isDebugMode()); //}); }); } } @Controller public class DemoController{ @Mapping("/hello") public String hello(){ return "Hello world!"; } } ``` -------------------------------- ### Configuration Example Source: https://solon.noear.org/article/424 Configuration example for solon.cloud.powerjob. ```yaml solon.app: name: demoapp group: demo solon.cloud.powerjob: server: 127.0.0.1:7700 password: 123456 job: port: 28888 protocol: akka solon.logging.logger: "io.netty.*": level: INFO ``` -------------------------------- ### Build Menu Data Example Source: https://solon.noear.org/article/891?format=md Example of building menu data using GritClient to get URI group list and first URI by group. ```java List groupList = GritClient.global().auth().getUriGroupList(subjectId); for (ResourceGroup group : groupList) { ResourceEntity res = GritClient.global().auth().getUriFristByGroup(subjectId, group.resource_id); if (Utils.isEmpty(res.link_uri) == false) { //res... } } ``` -------------------------------- ### Configuration Example Source: https://solon.noear.org/article/152 Example configuration for Solon's cloud file storage with Qiniu Kodo. ```yaml solon.cloud.qiniu.kodo.file: bucket: world-data-dev regionId: "cn-east-2" # v1.10.3 开始支持 endpoint: "https://xxx.yyy.zzz" accessKey: iWeU7cOoPLRokg2Hdat0jGQC secretKey: ZZIH6mT4VLAy68mVP80F7LiB5SpSEM7N ``` -------------------------------- ### Configuration Example 1 Source: https://solon.noear.org/article/147 Basic configuration example for solon.app and solon.cloud.consul. ```yaml solon.app: name: "demoapp" group: "demo" solon.cloud.consul: server: "localhost" #consul 服务地址 config: load: "demoapp.yml" #加载配置到应用属性(多个以","隔开) ``` -------------------------------- ### Stream Forwarding Example Source: https://solon.noear.org/article/730?format=md Example of using httputils to stream get and forward content without accumulating data, saving memory. ```java @Controller public class DemoController { @Mapping("/hello") public Flux hello(String name) throws Exception{ return HttpUtils.http("https://solon.noear.org/") .execAsTextStream("GET"); } } ``` -------------------------------- ### Run Ollama Source: https://solon.noear.org/article/917 Command to run a local LLM model using Ollama. ```bash ollama run llama3.2 # 或 deepseek-r1:7b ``` -------------------------------- ### Configuration File Example Source: https://solon.noear.org/article/31 Example of an application configuration file (app.yml or app.properties) with nested properties. ```yaml track: name: xxx url: http://a.a.a db1: jdbcUrl: "jdbc:mysql:..." username: "xxx" password: "xxx" ``` -------------------------------- ### Configuration Examples Source: https://solon.noear.org/article/537 Configuration examples for the lettuce-solon-plugin, showing two different modes. ```yaml redis.ds2: # Redis模式 (standalone, cluster, sentinel) redis-mode: standalone redis-uri: redis://localhost:6379/0 lettuce.rd2: # Redis模式 (standalone, cluster, sentinel) redis-mode: standalone config: host: localhost port: 6379 # socket: xxxx # client-name: myClientName # database: 0 # sentinel-masterId: 'mymaster' # username: 'myusername' # password: 'mypassword' # ssl: false # verify-mode: FULL # startTls: false # timeout: 10000 # sentinels: # - host: localhost # port: 16379 # password: 'mypassword' # - host: localhost # port: 26379 # password: 'mypassword' ``` -------------------------------- ### Code Application - Main Class Source: https://solon.noear.org/article/148 Example of starting the Solon application. ```java public class DemoApp { public void main(String[] args) { //启动时,服务会自动注册 SolonApp app = Solon.start(DemoApp.class, args); } } ``` -------------------------------- ### Application Example for Added Objects Source: https://solon.noear.org/article/672 A simple example showing how to use an added utility object (XUtil) to generate a GUID. ```java return XUtil.guid(); ``` -------------------------------- ### Client Example Source: https://solon.noear.org/article/1126 Example of configuring an McpClientProvider and using it to call a tool, including integration with an LLM. ```java McpClientProvider mcpClient = McpClientProvider.builder() .channel(McpChannel.STREAMABLE) .apiUrl("http://localhost:8081/mcp") .build(); //测试 String resp = mcpClient.callToolAsText("getWeather", Utils.asMap("location", "杭州")).getContent(); System.out.println(resp); //对接 LLM ChatModel chatModel = ChatModel.of(apiUrl).provider(...).model(...) .defaultToolsAdd(mcpClient) //绑定 mcp 工具 .build(); ChatResponse resp = chatModel .prompt("今天杭州的天气情况?") .call(); ``` -------------------------------- ### Equivalence of startup parameters and application configurations Source: https://solon.noear.org/article/176?format=md Illustrates that startup parameters with dots (.) can also be set as application configurations, showing three equivalent ways to set the 'solon.env' configuration. ```bash java -Dsolon.env=dev -jar demo.jar ``` ```bash java -jar demo.jar --solon.env=dev ``` ```bash java -jar demo.jar --env=dev ``` -------------------------------- ### Configuration Example 2 Source: https://solon.noear.org/article/147 More comprehensive configuration example including app metadata, tags, and consul credentials. ```yaml solon.app: name: "demoapp" group: "demo" meta: #添加应用元信息(可选) version: "v1.0.2" author: "noear" tags: "aaa,bbb,ccc" #添加应用标签(可选) solon.cloud.consul: server: "localhost" #consul 服务地址 username: "test" password: "test" config: load: "demoapp.yml" #加载配置到应用属性(多个以","隔开) ``` -------------------------------- ### Getting Serializer Instance Source: https://solon.noear.org/article/875 Examples of how to manually obtain the configured serialization interface. ```java Serializer serializer = Solon.app().serializers().get(SerializerNames.AT_ABC); Serializer serializer = Solon.context().getBean(AbcBytesSerializer.class); ``` -------------------------------- ### Code Application Source: https://solon.noear.org/article/492 Example of using KieTemplate to get KieSession in a Spring component. ```java @Component public class DemoCom{ //使用注解方式引入 KieTemplate @Inject private KieTemplate kieTemplate; public void test(){ //指定规则文件名,就可以获取对应的 Session,可以传入多个规则文件,包括决策表 KieSession kieSession = kieTemplate.getKieSession("rule1.drl", "rule2.drl"); //... } } ``` -------------------------------- ### HelloworldController Example Source: https://solon.noear.org/article/47?format=md Example of a controller for the helloworld view. ```java @Controller public class HelloworldController { @Mapping("/helloworld") public Object helloworld(){ ModelAndView vm = new ModelAndView("helloworld.ftl"); //Note: with suffix vm.put("title","demo-app"); vm.put("message","hello world!"); return vm; } } ``` -------------------------------- ### Book Controller Example Source: https://solon.noear.org/article/309?format=md This Java code demonstrates a controller for managing books, including methods for viewing, adding, updating, and deleting books. ```java @Mapping("books") @Controller public class Demo{ //查看一本图书:GET http://demo.com/books?id=1 @Get @Mapping public String one(Long id){ return "one"; } //新增一本书:POST http://demo.com/books //Data: name=shuxue @Post @Mapping public String add(Book book){ return "add"; } //修改一本书:PUT http://demo.com/books //Data:id=1,name=shuxue @Put @Mapping public String update(@NotNull Long id, String name){ return "update"; } //查看一本图书:删除一本书:DELETE http://demo.com/books //Data:id=1 @Delete @Mapping public String del(@NotNull Long id){ return "del"; } } ``` -------------------------------- ### Code Application Source: https://solon.noear.org/article/130 Example of how to get and set session attributes in a Solon controller. ```java @Controller public class DemoController{ @Mapping("/test") public void test(Context ctx){ //Get session long user_id = ctx.sessionAsLong("user_id", 0L); ctx.sessionSet("user_id", 1001L); } } //For more interfaces, please refer to SessionState definition ``` -------------------------------- ### Client Example Source: https://solon.noear.org/article/1126?format=md Example of configuring a client to connect to the McpServerEndpoint and call a tool, including integration with a ChatModel. ```java McpClientProvider mcpClient = McpClientProvider.builder() .channel(McpChannel.STREAMABLE) .apiUrl("http://localhost:8081/mcp") .build(); //测试 String resp = mcpClient.callToolAsText("getWeather", Utils.asMap("location", "杭州")).getContent(); System.out.println(resp); //对接 LLM ChatModel chatModel = ChatModel.of(apiUrl).provider(...).model(...) .defaultToolsAdd(mcpClient) //绑定 mcp 工具 .build(); ChatResponse resp = chatModel .prompt("今天杭州的天气情况?") .call(); ``` -------------------------------- ### Get a single resource file and convert to String Source: https://solon.noear.org/article/516 Example of how to get a single resource file and read its content as a String using ResourceUtil.getResourceAsString. ```java String rst = ResourceUtil.getResourceAsString("demo.json"); ``` -------------------------------- ### Manual Configuration Example Source: https://solon.noear.org/article/274?format=md Example of manually loading a configuration file named demo.yml. ```yaml user.name: "noear" user.level: 0 ``` -------------------------------- ### Custom JSP Tag Example (FooterTag) Source: https://solon.noear.org/article/251?format=md A Java example for creating a custom JSP tag, `FooterTag`, which demonstrates how to write content to the page context. ```java public class FooterTag extends TagSupport { @Override public int doStartTag() throws JspException { try { String path = Context.current().path(); //当前视图path StringBuffer sb = new StringBuffer(); sb.append("
"); sb.append("我是自定义标签,FooterTag;当前path=").append(path); sb.append("
"); pageContext.getOut().write(sb.toString()); } catch (Exception e){ e.printStackTrace(); } return super.doStartTag(); } @Override public int doEndTag() throws JspException { return super.doEndTag(); } } ``` -------------------------------- ### Richer Configuration Example Source: https://solon.noear.org/article/526?format=md A more comprehensive configuration example including app metadata and tags. ```yaml solon.app: name: "demoapp" group: "demo" meta: #添加应用元信息(可选) version: "v1.0.2" author: "noear" tags: "aaa,bbb,ccc" #添加应用标签(可选) solon.cloud.etcd: server: "localhost:2379" #etcd 服务地址 config: load: "demoapp.yml" #加载配置到应用属性(多个以","隔开) ``` -------------------------------- ### JSP View Example (helloworld.jsp) Source: https://solon.noear.org/article/251?format=md An example JSP file that uses EL expressions to display data passed from the controller and includes the custom footer tag. ```html <%@ page import="java.util.Random" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="ct" uri="/tags" %> ${title}
context path: ${ctx.path()}
properties: custom.user :${user}
${m.name} : ${message} (我想静静
``` -------------------------------- ### Solon Application Startup Source: https://solon.noear.org/article/learn-solon-aop?format=md This is a basic example of how to start a Solon application. ```java @SolonMain public class App{ public static void main(String[] args){ Solon.start(App.class, args); } } ``` -------------------------------- ### Startup Initialization - Loading Configuration Files Source: https://solon.noear.org/article/301 Example of loading additional configuration files during the Solon application startup initialization. ```java Solon.start(App.class, args, app->{ app.cfg().loadAdd("demo.yml"); }); ``` -------------------------------- ### Solon.config.add Example (Command Line) Source: https://solon.noear.org/article/894?format=md Example of using solon.config.add via command line arguments to specify configuration files. ```java java -jar demo.jar -solon.config.add=file:config/demo.yml,classpath:config/demo.yml,config/demo.yml ``` ```java java -Dsolon.config.add=file:config/demo.yml,classpath:config/demo.yml,config/demo.yml -jar demo.jar ``` -------------------------------- ### Get Serializer Instance Source: https://solon.noear.org/article/867?format=md Examples of how to manually obtain the configured serialization interface. ```java Serializer serializer = Solon.app().serializers().get(SerializerNames.AT_KRYO); Serializer serializer = Solon.context().getBean(KryoBytesSerializer.class); ``` -------------------------------- ### Activiti Example Source: https://solon.noear.org/article/427 A user-written example demonstrating the integration of Activiti with Solon. ```markdown ::activiti _< />_ markdown 2023年2月2日 下午2:44:18 Activiti 不需要适配,可直接使用。附用户编写的示例: https://gitee.com/awol2010ex/solon-gradle-activiti522-demo-1 ``` -------------------------------- ### Get Serializer Instance Source: https://solon.noear.org/article/636?format=md Examples of how to manually obtain configured serializer interfaces. ```java Serializer serializer = Solon.app().serializers().get(SerializerNames.AT_FURY); Serializer serializer = Solon.context().getBean(FuryBytesSerializer.class); ``` -------------------------------- ### Uninstallation Commands Source: https://solon.noear.org/article/1404?format=md Commands for uninstalling SolonCode on macOS, Linux, and Windows. ```bash # Mac / Linux sh ~/.soloncode/bin/uninstall.sh ``` ```powershell # Windows (PowerShell) & "$HOME/.soloncode/bin/uninstall.ps1" ``` -------------------------------- ### Brief Configuration Example Source: https://solon.noear.org/article/1240?format=md A brief configuration example for solon.cloud.jmdns. ```yaml solon.app: group: demo # 配置服务使用的默认组 name: helloapp # 发现服务使用的应用名 solon.cloud.jmdns: server: localhost # 不需要端口号,JmDNS监听该IP进行服务发现 写 localhost 或某个本地 IP ```