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); } |

相关推荐
默 语15 小时前
基于 Spring Boot 3 + LangChain4j 快速构建企业级 AI 应用实战
人工智能·spring boot·后端
薪火铺子16 小时前
SpringBoot WebServer启动与监听器原理深度解析
spring boot·后端·tomcat
KmSH8umpK16 小时前
SpringBoot 分布式锁实战:从单机锁到Redis分布式锁全覆盖,解决超卖、重复下单、幂等并发问题
spring boot·redis·分布式
jay神16 小时前
基于团队模式的C程序设计课程辅助教学管理系统
java·spring boot·vue·web开发·管理系统
长河18 小时前
基于 Jib 实现无 Dockerfile 的 Spring Boot 应用容器化
java·spring boot·后端
Arya_aa18 小时前
一:病虫害 AI 识别系统项目初期准备与Docker初识,VM虚拟机
spring boot
敖正炀18 小时前
Spring MVC 启动全景:DispatcherServlet 与父子容器
spring boot
绿草在线20 小时前
基于SpringBoot4+Mybatis+Thymeleaf的用户管理系统开发实战
java·spring boot·thymeleaf
麦麦大数据20 小时前
基于以太坊区块链+Spring Boot+Solidity智能合约的投票系统设计与实现
spring boot·后端·区块链·智能合约·投票系统