Spring Boot是一个全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,Spring Boot框架使java程序员在开发时不需要定义样板化的配置,这使得Spring Boot十分流行,这篇文章来介绍关于Spring Boot非web应用程序该怎样创建的问题,解决大家关于Spring Boot非web应用程序在框架中创建的疑问。
有时候一些项目并不需要提供web服务,例如跑定时任务的项目,如果都按照web项目启动会有些浪费资源,这个时候为了达到非web运行的效果,就体现出Spring Boot非web应用程序创建的作用了。
在Spring Boot框架中,要创建一个非Web应用程序(纯Java程序),有两种方式:
Spring Boot非web应用程序的创建方式一:
创建纯java项目的起步依赖
org.springframework.boot
spring-boot-starter
直接在main方法中,根据SpringApplication.run()方法获取返回的Spring容器对象,再获取业务bean进行调用;
public static void main(String[] args) {
ApplicationContext context =
SpringApplication.run(Application.class, args);
HelloService helloService =
(HelloService)context.getBean("helloService");
String hi = helloService.getMessage("springboot main");
System.out.println(hi);
}
Spring Boot非web应用程序的创建方式二:
1、Spring boot的入口类实现CommandLineRunner接口;
2、覆盖CommandLineRunner接口的run()方法,run方法中编写具体的处理逻辑即可;
@Autowired
private HelloService helloService;
@Override
public void run(String... args) throws Exception {
System.out.println("hello world!");
String ss = helloService.getMessage("aaa111");
System.out.println(ss);
}
下面是在Spring Boot创建一个非Web应用程序的代码(实现了CommandLineRunner,并覆盖run()方法)
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootConsoleApplication.class, args);
}
//access command line arguments
@Override
public void run(String... args) throws Exception {
//do something
}
}
以上就是Spring Boot非web应用程序创建的两种方式,希望通过这篇文章的介绍,大家可以学会在Spring Boot框架中创建非web应用程序的操作。Spring Boot致力于在蓬勃发展的快速应用开发领域成为领导者,这是java程序员必须会使用的框架,希望大家可以多多学习Spring Boot视频教程,零基础的新手朋友们早日完成SpringBoot框架从入门到实践的过程。