文章目录
在 Spring Boot 框架中,要创建一个非 Web 应用程序(纯 Java 程序) ,有两种方式
一、SpringBoot集成javaSE
1. SpringApplication.run方法获取SpringBoot容器对象
(1)依赖
加入Springboot非web工程起步依赖
<!--Springboot非web工程起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
(2)获取容器对象
SpringApplication.run()方法的返回值就是 Spring 容器对象,然后再从容器对象中获取bean,并调用其方法
StudentService类:
@Service()
public class StudentServiceImpl implements StudentService {
@Override
public String sayHello() {
return "Hello SpringBoot";
}
}
Application类:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
/**
* SpringBoot 程序启动后,返回值是 ConfigurableApplicationContext,它也是一
个 Spring 容器对象
* 它其它相当于原来 Spring 中启动容器 ClassPathXmlApplicationContext context
= new ClassPathXmlApplicationContext("");
*/
//获取 SpringBoot 程序启动后的 Spring 容器
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
//从 Spring 容器中获取指定 bean 的对象
StudentService studentService = (StudentService)context.getBean("studentServiceImpl");
//调用业务 bean 的方法,并输出
System.out.println(studentService.sayHello());
}
}
2. 实现 CommandLineRunner 接口
(1)加入依赖
加入的依赖与方法1 的依赖相同
(2)修改启动类
- 启动类实现CommandLineRunner接口
- 覆盖接口中的run()方法
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private StudentService studentService;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println(studentService.sayHello());
}
}
二、打包与部署
1. 配置pom.xml
- pom.xml 的配置与打 war 包时配置稍有不同,要做如下修改
- 打包的类型指定为 jar
- 修改 pom.xml 文件中打包插件的版本
默认 SpingBoot 提供的打包插件版本为 2.2.2.RELEASE,这个版本打的 jar 包 jsp 不能访问,我们这里修改为 1.4.2.RELEASE(其它版本测试都有问题)
2. 打包
通过 Maven 的 package 命令将 war 包打包到 target 目录下,要运行jar包,要在jar包所在目录下的命令行执行:java -jar jar包的名字