版权声明:本文为博主原创文章,转载请说明出处 https://blog.csdn.net/u010002184/article/details/86515845
@Service
public class AirService implements InitializingBean {
public static final Logger logger = LoggerFactory.getLogger(AirService.class);
public static List<Integer> toBeUsedList2 = new ArrayList<>();
@Override
public void afterPropertiesSet() throws Exception {//后执行
logger.info("afterPropertiesSet...");
toBeUsedList2.add(1);
toBeUsedList2.add(2);
toBeUsedList2.add(3);
}
@Scheduled(cron = "0/2 * * * * ?")
public void f2() {
logger.info(toBeUsedList2.toString());
}
public static List<Integer> toBeUsedList = new ArrayList<>();
static {//先执行
logger.info("static...");
toBeUsedList.add(1);
toBeUsedList.add(2);
toBeUsedList.add(3);
}
@Scheduled(cron = "0/3 * * * * ?")
public void f1() {
logger.info(toBeUsedList.toString());
}
}
INFO: 2019-01-16 10:14:59 [com.weather.weatherexpert.service.AirService:116] static...
INFO: 2019-01-16 10:14:59 [com.weather.weatherexpert.service.AirService:101] afterPropertiesSet...
INFO: 2019-01-16 10:15:04 [org.springframework.boot.web.embedded.tomcat.TomcatWebServer:206] Tomcat started on port(s): 8080 (http) with context path ''
INFO: 2019-01-16 10:15:04 [com.weather.weatherexpert.WeatherExpertApplication:59] Started WeatherExpertApplication in 11.393 seconds (JVM running for 13.727)
INFO: 2019-01-16 10:15:06 [com.weather.weatherexpert.service.AirService:125] [1, 2, 3]
INFO: 2019-01-16 10:15:06 [com.weather.weatherexpert.service.AirService:109] [1, 2, 3]
INFO: 2019-01-16 10:15:08 [com.weather.weatherexpert.service.AirService:109] [1, 2, 3]
INFO: 2019-01-16 10:15:09 [com.weather.weatherexpert.service.AirService:125] [1, 2, 3]
INFO: 2019-01-16 10:15:10 [com.weather.weatherexpert.service.AirService:109] [1, 2, 3]
INFO: 2019-01-16 10:15:12 [com.weather.weatherexpert.service.AirService:125] [1, 2, 3]
INFO: 2019-01-16 10:15:12 [com.weather.weatherexpert.service.AirService:109] [1, 2, 3]
INFO: 2019-01-16 10:15:14 [com.weather.weatherexpert.service.AirService:109] [1, 2, 3]
INFO: 2019-01-16 10:15:15 [com.weather.weatherexpert.service.AirService:125] [1, 2, 3]
会发现static代码块比InitializingBean先运行。
初始化的顺序是:
Constructor > @PostConstruct > InitializingBean > init-method
spring常用接口 InitializingBean的作用:https://www.cnblogs.com/JKayFeng/p/5974104.html