Spring Boot 非web应用程序

发布于:2025-04-01 ⋅ 阅读:(20) ⋅ 点赞:(0)

​​​​​在 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);

}