先看下@PostConstruct的注解java
* The PostConstruct annotation is used on a method that needs to be executed * after dependency injection is done to perform any initialization. This * method MUST be invoked before the class is put into service. This * annotation MUST be supported on all classes that support dependency * injection. The method annotated with PostConstruct MUST be invoked even * if the class does not request any resources to be injected. Only one * method can be annotated with this annotation. The method on which the * PostConstruct annotation is applied MUST fulfill all of the following * criteria -
本身翻译一下,意思是:android
PostConstruct注解用于方法上,该方法在初始化的依赖注入操做以后被执行。这个方法必须在class被放到service以后被执行,这个注解所在的类必须支持依赖注入。web
父类class,被@component注解修饰,说明会被spring扫描并建立。在默认构造方法里加上输出打印,init方法被@PostConstruct修饰spring
@Component public class ParentBean implements InitializingBean{ public ParentBean() { System.out.println("ParentBean construct"); } @PostConstruct public void init(){ System.out.println("ParentBean init"); } public void afterPropertiesSet() throws Exception { System.out.println("ParentBean afterPropertiesSet"); } }
子类class,也被 @component注解修饰,其他配置和父类class同样app
@Component public class SonBean extends ParentBean{ public SonBean() { System.out.println("SonBean construct"); } @PostConstruct public void init(){ System.out.println("SonBean init"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("SonBean afterPropertiesSet"); } }
而后咱们使用maven命令 jetty:run,控制台输出以下:框架
[INFO] Initializing Spring root WebApplicationContext ParentBean construct ParentBean init ParentBean afterPropertiesSet ParentBean construct SonBean construct SonBean init SonBean afterPropertiesSet [INFO] Set web app root system property: 'webapp.root' = [J:\androidworkspace\com\src\main\webapp\] [INFO] Initializing log4j from [classpath:log4j.properties] [INFO] Started SelectChannelConnector@0.0.0.0:8088 [INFO] Started Jetty Server [INFO] Starting scanner at interval of 3 seconds.
能够看出优先执行依然是构造方法,这个是java的语言决定的,毕竟spring只是创建在java之上的框架。而后才是被PostConstruct修饰的方法,要注意的是这个方法在对象的初始化和依赖都完成以后才会执行,因此没必要担忧执行这个方法的时候有个别成员属性没有被初始化为null的状况发生。在init方法以后执行的才是afterPropertiesSet方法,这个方法必须实现InitializingBean接口,这个接口不少spring的bean都实现了他,从他的方法名就能看出在属性都被设置了以后执行,也属于springbean初始化方法。webapp
其实spring提供了不少接口以供开发者在bean初始化后调用,能够在官网上查阅相关文档。maven