Spring Boot 非web应用程序

​​​​​在 Spring Boot 框架中,要创建一个非Web应用程序(纯Java程序)

main方法运行,不启动tomcat,main方法执行结束,程序就退出了;

方式一

1、SpringBoot开发纯Java程序,应该采用如下的起步依赖:

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <!-- Springboot开发java项目的起步依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> |

2、直接在main方法中,根据SpringApplication.run()方法获取返回的Spring容器对象,再获取业务bean进行调用;

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| public static void main(String\[\] args) { ConfigurableApplicationContext context = SpringApplication.run(Application.class, args); UserService userService = (UserService)context.getBean("userService"); String hello = userService.getMessage("Hello, Spring Boot"); System.out.println(hello); } |

​​​​​​​方式二

1、SpringBoot开发纯Java程序,应该采用如下的起步依赖:

|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| <!-- Springboot开发java项目的起步依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> |

2、Spring Boot 的入口类实现CommandLineRunner接口;

3、覆盖CommandLineRunner接口的run()方法,run方法中编写具体的处理逻辑即可;

|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| @Autowired private UserService userService; @Override public void run(String... args) throws Exception { String msg = userService.getMessage("zhangshan"); System.out.println(msg); } |

相关推荐
whyfail2 小时前
前端学 Spring Boot(8):接口为什么越用越慢?
前端·spring boot·后端
Muscleheng3 小时前
Spring Boot 3.x 集成 DeepSeek 实现 Function Calling(工具调用)
人工智能·spring boot·后端·ai·spring ai·deepseek
@航空母舰3 小时前
SpringBoot通过Map实现天然的策略模式
java·spring boot·后端
IT_Octopus5 小时前
Spring Boot 中 ThreadLocal 请求上下文的完整生命周期
java·spring boot·spring
IT_Octopus8 小时前
Spring Boot 线程池关闭:destroyMethod 的作用与最佳实践
java·spring boot·后端
米码收割机8 小时前
【项目】vue3+springboot零食商城系统(源码+文档++PPT)【独一无二】
java·spring boot·后端
霸道流氓气质9 小时前
SpringBoot中事务内同步处理 + 事务后异步调用外部系统的通用模式示例
java·spring boot·后端
凤山老林9 小时前
SpringBoot实战:接口参数校验与优雅处理
java·spring boot·后端
Arya_aa11 小时前
jdk动态代理和AOP面向切面编程
spring boot
Full Stack Developme12 小时前
SpringBoot 整合 Druid 并列出参数清单
java·spring boot·后端