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

相关推荐
终将老去的穷苦程序员12 小时前
基于SpringBoot的餐饮管理系统
java·spring boot·后端
心之伊始12 小时前
Spring AI Tool Calling 实战:让 Java Agent 调用本地 Bean 工具方法
java·spring boot·agent·spring ai·tool calling
熠熠仔13 小时前
Spring Boot 与 MyBatis-Plus 空间几何数据集成指南
spring boot·后端·mybatis
天青色等烟雨..13 小时前
智慧农林核心遥感技术99个案例实践
运维·人工智能·spring boot·后端·自动化
雪宫街道15 小时前
SpringBoot 向 IOC 容器注册组件的两种姿势:@Configuration 与 @Import
java·spring boot·后端·spring
接着奏乐接着舞16 小时前
springboot mp mybatis plaus
windows·spring boot·mybatis
金融支付架构实战指南16 小时前
Milvus 向量检索服务 + SpringBoot 实战:电商商品语义检索与相似商品推荐
spring boot·后端·milvus·向量检索
愛~杦辷个訾17 小时前
Java Springboot使用阿里云oss对图片进行等质量压缩,转换成webp格式的压缩图。
java·spring boot·阿里云·oss
霸道流氓气质17 小时前
Spring Boot Multipart 表单中文乱码问题全解析
java·spring boot·后端
RuoyiOffice17 小时前
从 0 到 1 搭建 RuoyiOffice:30 分钟跑通后端+前端+移动端
前端·spring boot·uni-app·开源·oa·ruoyioffice·hrm