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

相关推荐
enjoy嚣士9 小时前
springboot之Exel工具类
java·spring boot·后端·easyexcel·excel工具类
小涛不学习11 小时前
Spring Boot 详解(从入门到原理)
java·spring boot·后端
弹简特14 小时前
【JavaEE18-后端部分】 MyBatis 入门第二篇:使用注解完成增删改查(含有参数传递底层原理)
spring boot·mybatis
于先生吖14 小时前
SpringBoot+Vue 前后端分离短剧漫剧系统开发实战
vue.js·spring boot·后端
小王不爱笑13215 小时前
SpringBoot 自动装配深度解析:从底层原理到自定义 starter 实战(含源码断点调试)
java·spring boot·mybatis
while(1){yan}15 小时前
个人抽奖系统测试报告
spring boot·java-ee·压力测试
asom2216 小时前
DDD(领域驱动设计) 核心概念详解
java·开发语言·数据库·spring boot
Fu-dada16 小时前
Spring Boot 开发接口指南
spring boot
大傻^17 小时前
LangChain4j Spring Boot Starter:自动配置与声明式 Bean 管理
java·人工智能·spring boot·spring·langchain4j
yhole17 小时前
springboot 修复 Spring Framework 特定条件下目录遍历漏洞(CVE-2024-38819)
spring boot·后端·spring