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

相关推荐
绝知此事1 小时前
Netty实战:从零构建高性能TCP通信服务(含心跳检测)
java·网络·spring boot·网络协议·tcp/ip
AI产品实战2 小时前
流程引擎Flowable vs Warm-Flow 选型
spring boot
Circ.4 小时前
SpringBoot 实现文件上传与下载(完整源码 + 详细教程)
java·spring boot·后端
zzqssliu4 小时前
Spring Boot + XXL-JOB 搭建淘宝代购系统任务调度中心
java·spring boot·后端
努力发光的程序员10 小时前
互联网大厂Java面试故事:Spring Boot与微服务全栈技术实战问答
java·spring boot·spring cloud·微服务·kafka·hibernate·面试技巧
一只大袋鼠10 小时前
SpringBoot 入门学习笔记(二)Web 开发基础
spring boot·笔记·学习
XiYang-DING11 小时前
Spring Boot 集成 Hutool 实现图片验证码
java·spring boot·后端
AI产品实战12 小时前
95coder一句话生成MOM系统,AI用时6分50秒,Token只消耗25107
vue.js·spring boot·ai编程·ruoyi
身如柳絮随风扬13 小时前
Docker 化部署 Spring Boot + Vue 全栈应用:从打包到容器化上线
vue.js·spring boot·docker
一只大袋鼠13 小时前
SpringBoot 入门学习笔记(三)Web 开发下篇
spring boot·笔记·学习