首页 > 其他 > 详细

实现在项目启动后或是生成对象后完成某些执行的功能实现CommandLineRunner接口和注解@PostConstruct

时间:2020-08-26 14:30:02      阅读:83      评论:0      收藏:0      [点我收藏+]

  在项目中我们有时候需要实现项目启动后就执行的功能,比如将热点数据存入redis中。

方式一:定义一个类实现CommandLineRunner接口,实现功能的代码在run方法中。cnblogs中参考

补充:SpringBoot在项目启动后会遍历所有实现CommandLineRunner的实体类并执行run方法,如果需要按照一定的顺序去执行,那么就需要在实体类上使用一个@Order注解(或者实现Order接口)来表明顺序。

技术分享图片
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class RedisDataRunner implements CommandLineRunner {
    @Autowired
    private SetRedisData redisData;

    @Override
    public void run(String... strings) throws Exception {
        redisData.setOrgData();
    }
}
View Code

 

方法二:在方法中增加注解@PostConstruct,修饰一个非静态的void()方法。csdn中参考链接

@PostConstruct注解的方法会在依赖注入完成后被自动调用:Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)

技术分享图片
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class RedisDataRunner {

    @Autowired
    private SetRedisData redisData;

    public static final ExecutorService pool = Executors.newFixedThreadPool(10);

    @PostConstruct
    public void init() {
        
        pool.execute(new Runnable() {
            @Override
            public void run() {
                redisData.setOrgData();
            }
        });
    }
}
View Code

 

实现在项目启动后或是生成对象后完成某些执行的功能实现CommandLineRunner接口和注解@PostConstruct

原文:https://www.cnblogs.com/guobm/p/13564883.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!