SpringBoot集成javaSE

上一篇:SpringBoot集成javaEE

在 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)修改启动类

  1. 启动类实现CommandLineRunner接口
  2. 覆盖接口中的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

  1. pom.xml 的配置与打 war 包时配置稍有不同,要做如下修改
  2. 打包的类型指定为 jar
  3. 修改 pom.xml 文件中打包插件的版本
    默认 SpingBoot 提供的打包插件版本为 2.2.2.RELEASE,这个版本打的 jar 包 jsp 不能访问,我们这里修改为 1.4.2.RELEASE(其它版本测试都有问题)

2. 打包

通过 Maven 的 package 命令将 war 包打包到 target 目录下,要运行jar包,要在jar包所在目录下的命令行执行:java -jar jar包的名字

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值