Spring Boot非Web项目运行的方法

发布时间: 3年前 (2021-08-17)浏览: 1566评论: 0

有时候一些项目并不需要提供 Web 服务,例如跑定时任务的项目,如果都按照 Web 项目启动未免画蛇添足浪费资源

为了达到非 Web 运行的效果,首先调整 Maven 依赖,不再依赖 spring-boot-starter-web,转而依赖最基础的 spring-boot-starter:

1
2
3
4
5
6
<dependencies>
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
 </dependency>
</dependencies>


这时候 SpringBootApplication 的程序入口在执行完main方法后直接exit了, 现在需要hold应用程序防止直接退出, 有两种方法:

  • 实现 CommandLineRunner   springboot 2.0.0之后用  ApplicationRunner 接口在run方法中通过 Thread.currentThread().join() 使得应用程序在执行run方法时阻塞, 这样程序就可以保持运行

  • 通过 Spring Boot 提供的配置(推荐):

    • Spring Boot 2.0.0 以上的版本: spring.main.web-application-type=NONE // REACTIVE, SERVLET

    • Spring Boot 2.0.0 之前的版本: spring.main.web-environment=false

此时按照原先的方式启动 SpringBootApplication 会发现启动加载完之后会立即退出,这时需要做点工作让主线程阻塞让程序不退出:

1
2
3
4
5
6
7
8
9
10
@SpringBootApplication
public class SampleApplication implements CommandLineRunner {
 public static void main(String[] args) throws Exception {
  SpringApplication.run(SampleApplication.class, args);
 }
 @Override
 public void run(String... args) throws Exception {
  Thread.currentThread().join();
 }
}




1、springboot 1.x中以非web方式启动 

// 启动方式1
SpringApplication app = new SpringApplication(Application.class);
app.setWebEnvironment(false);// 设置ApplicationContext类型
ApplicationContext ctx = app.run(args);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 启动方式2<br>@SpringBootApplication 
public class Application implements ApplicationRunner{ 
   
    public static void main(String[] args) { 
        new SpringApplicationBuilder() 
            .sources(Application.class).web(false).run(args); 
    
   
    @Override 
    public void run(ApplicationArguments args) throws Exception { 
        while(true) { 
            System.out.println("now is " + new Date().toLocaleString()); 
        Thread.sleep(1000); 
    
    
   

2、springboot 2.0中以非web方式启动 

-web(false)/setWebEnvironment(false) is deprecated and instead Web-Application-Type can be used to specify 

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 配置spring.main.web-application-type=NONE# 代码@SpringBootApplication 
public class Application implements ApplicationRunner{ 
   
    public static void main(String[] args) { 
        new SpringApplicationBuilder(Application.class
            .web(WebApplicationType.NONE) // .REACTIVE, .SERVLET 
            .bannerMode(Banner.Mode.OFF) 
            .run(args); 
    
   
    @Override 
    public void run(ApplicationArguments args) throws Exception { 
        while(true) { 
            System.out.println("now is " + new Date().toLocaleString()); 
            Thread.sleep(1000); 
        
    
       
}


标签:

上一篇: GC垃圾收集器&JVM调优汇总
下一篇: Spring-boot启动添加参数

相关文章暂无相关
评论列表暂无评论
发表评论
验证码

«   2024年4月   »
1234567
891011121314
15161718192021
22232425262728
2930
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
    文章归档
    网站收藏
    友情链接
    • RainbowSoft Studio Z-Blog
    • 订阅本站的 RSS 2.0 新闻聚合
    ︿
    Top