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

  在项目中我们有时候需要实现项目启动后就执行的功能,比如将热点数据存入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

 

posted @ 2020-08-26 14:12  sun-sailing  阅读(551)  评论(0)    收藏  举报