1、实现InitializingBean接口,重写afterPropertiesSet()在bean初始化时会执行该方法
@Configuration
public class RecoveryManagerJob implements InitializingBean {
/**
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("————————————————————————————i am after properties set");
}
}
2、添加其他注解 运行时 查看 跟afterPropertiesSet()的实现顺序
新建接口:
public interface Car {
public String carName();
}
新建class 实现该接口
@Service
public class BMW implements Car{
@Override
public String carName() {
return "bmw";
}
}
在 RecoveryManagerJob类中添加 以下内容 ,查看执行顺序
@Configuration
public class RecoveryManagerJob implements InitializingBean {
/**
* //Constructor -> @Autowired -> @PostConstruct -> afterPropertiesSet() -> init-method
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("————————————————————————————i am after properties set");
}
@Autowired
private Car car;
// 先生成对象RecoveryManagerJob1 再 注入Car
public RecoveryManagerJob() {
System.out.println("————————————————————————————此时car未被注入,打印car会空指针" );
}
@PostConstruct
public void start(){
System.out.println("————————————————————————————i am postconstrruct, i will revcovery the jobs..."+ car.carName());
}
// 最后执行
@Bean
public void init() throws Exception {
System.out.println("————————————————————————————i am init-method");
}
}
执行结果如下:可以看到具体 顺序://Constructor(构造器) -> @Autowired -> @PostConstruct -> afterPropertiesSet() -> init-method
2020-10-10 17:41:11.051 INFO 2505 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1510 ms
————————————————————————————此时car未被注入,打印car会空指针
————————————————————————————i am postconstrruct, i will revcovery the jobs...bmw
————————————————————————————i am after properties set
————————————————————————————i am init-method
2020-10-10 17:41:11.272 INFO 2505 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-10-10 17:41:11.824 INFO 2505 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-10-10 17:41:11.860 INFO 2505 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8082 (http) with context path ''
2020-10-10 17:41:11.870 INFO 2505 --- [ restartedMain] com.wx.web.RemindApplication : Started RemindApplication in 2.687 seconds (JVM running for 3.324)