Bean Spring container life cycle
1. init-method and the method destory-method
When Spring bean initialization bean or destroyed, sometimes need to do some processing work, so spring can call the bean's two life-cycle approach in the creation and removal of the bean.
Such as:
bean id="xxx" class="xxx" init-method="init" destory-method="destory" />
When bean is loaded into the container when the call init, when removed from the container bean call destory (scope = singleton effective). Init method name and destory can name their own
web container will automatically call, but the main function or test cases need to manually call
Specific code: SpringDemo3.demo2 ()
2. Spring Bean container life cycle (understand)
- instantiate bean object instantiation
- Package populate properties Properties
- If the Bean implementation BeanNameAware execution setBeanName
- If the Bean or ApplicationContextAware achieve BeanFacotryAware factory setting or context object setApplicationContext setBeanFactory
- If there class implements the BeanPostProcessor (post-treatment Bean), performed postProcessBeforeInitialization
- If the Bean implementation InitializingBean execution afterPropertiesSet
- Call the
<bean init-method="init">
designated initializer init, if the class exists to achieve BeanPostProcessor (processing Bean), the implementation of postProcessAfterInitialization - Business process execution
- If the Bean implementation DisposableBean, execution destroy
- Call the
bean destroy-method="customerDestroy">
specified methods of destruction customerDestroy
Among the most important are: Steps 5 and seventh.
Ide accomplish the above process, the printing is as follows:
Specific code: SpringDemo3.demo3 ()
3. beanpostprocessor role
beanpostprocessor class can be generated in the process of classes, the class generating agent, and can be enhanced class method.
The code below is a beanpostprocessor class, we enhanced the postProcessAfterInitialization initialization method. Enhanced save method in the bean.
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// System.out.println("第五步:初始化前的方法...");
return bean;
}
@Override
public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
// System.out.println("第八步:初始化后方法...");
//使用代理,构造匿名函数
if ("userDao".equals(beanName)) {
Object proxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("save".equals(method.getName())) {
System.out.println("权限校验==========");
// 传入属性
return method.invoke(bean, args);
}
return method.invoke(bean, args);
}
});
return proxy;
} else {
return bean;
}
}
}
Output is as follows: