1.InitializingBean 失效此介面的類,在初始化完成之後,會自動調用afterPropertiesSet()方法,但是在init-method方法之後(如果配置) @Component public class InitializingBeanTest implements Initi ...
1.InitializingBean
失效此介面的類,在初始化完成之後,會自動調用afterPropertiesSet()方法,但是在init-method方法之後(如果配置)
@Component
public class InitializingBeanTest implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet 被調用");
}
}
2.BeanPostProcessor
bean後置處理器,它是用來攔截所有 bean 的初始化的,在 bean 的初始化之前,和初始化之後做一些事情。這點從 BeanPostProcessor 介面的定義也可以看出來,它裡面就兩個方法:postProcessBeforeInitialization 和 postProcessAfterInitialization。
2.1:後置處理器的postProcessorBeforeInitailization方法是在bean實例化,依賴註入之後及自定義初始化方法(例如:配置文件中bean標簽添加init-method屬性指定Java類中初始化方法、
@PostConstruct註解指定初始化方法,Java類實現InitailztingBean介面)之前調用
2.2:後置處理器的postProcessorAfterInitailization方法是在bean實例化、依賴註入及自定義初始化方法之後調用
@Component
public class BeanPostProcessorTest implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("後置處理器處理bean=【"+beanName+"】開始");
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("後置處理器處理bean=【"+beanName+"】完畢");
return bean;
}
}
3.ApplicationContextAware
當一個類實現了這個介面之後,這個類就可以方便的獲得ApplicationContext對象,然後從applicationContext對象中利用getBean()獲取容器中的bean
@Component
public class SpringContextHelper implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
public static <T> T getInstance(String beanName, Class<T> beanType) {
return applicationContext.getBean(beanName, beanType);
}
public static <T> T getInstance(Class<T> bean) {
return applicationContext.getBean(bean);
}
}
4.BeanFactoryAware
同ApplicationContextAware對象一樣,實現此介面可以獲取到BeanFactory對象,然後利用getBean獲取我們需要bean
@Service
public class BeanFactoryHelper implements BeanFactoryAware {
private static BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
public static Object getBean(String beanName){
if(beanFactory == null){
throw new NullPointerException("BeanFactory is null!");
}
return beanFactory.getBean(beanName);
}
}
5.ApplicationRunner
在項目完全啟動後,調用實現此介面的方法。
@Component
public class CommonRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("啟動後執行。。。。。");
}
}
6.@PostConstruct
在bean初始化之前調用,具體和afterPropertiesSet(),還有init-method調用順序,可以看下spring的生命周期