在項目中咱們有時候須要實現項目啓動後就執行的功能,好比將熱點數據存入redis中。html
方式一:定義一個類實現CommandLineRunner接口,實現功能的代碼在run方法中。cnblogs中參考鏈接java
補充:SpringBoot在項目啓動後會遍歷全部實現CommandLineRunner的實體類並執行run方法,若是須要按照必定的順序去執行,那麼就須要在實體類上使用一個@Order註解(或者實現Order接口)來代表順序。redis
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(); } }
方法二:在方法中增長註解@PostConstruct,修飾一個非靜態的void()方法。csdn中參考連接spring
@PostConstruct註解的方法會在依賴注入完成後被自動調用:Constructor(構造方法) -> @Autowired(依賴注入) -> @PostConstruct(註釋的方法)ide
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(); } }); } }