Spring Boot 非web应用程序的实现
作者:楚楚ccc
SpringBoot框架中,要创建一个非Web应用程序(纯 Java 程序),有两种方式,下面就来介绍一下,感兴趣的可以来了解一下
在 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); }
到此这篇关于Spring Boot 非web应用程序的实现的文章就介绍到这了,更多相关Spring Boot 非web应用程序内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!