- spring初始化bena的方式之一 , 其二为 指定init-method方法;
- 优缺点
优点 : 实现接口,效率高 , 底层直接强转调用类的方法(AbstractAutowireCapableBeanFactory.invokeInitMethods中执行)
缺点 : 未解耦
1.实现InitializingBean接口,重写afterPropertiesSet方法;
2.在该bean属性注入完毕后执行;
3.afterPropertiesSet方法先于init-method执行;(invokeInitMethods方法中先判断是否实现InitializingBean接口,有则执行;
接着判断是否指定init-method方法,执行init-method)
4.afterPropertiesSet后于 BeanPostProcess的postProcessBeforeInitialization方法执行;
InitializingBean实现类:
package com.ws.model;
import org.springframework.beans.factory.InitializingBean;
public class User implements InitializingBean {
private String name;
private int age;
public User() {
System.out.println("User 构造器");
}
public User(String name) {
this(name, 0);
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
System.out.println("set 注入");
this.age = age;
}
public void initMethod() {
System.out.println("[initMethod] [age]=" + this.age + " [name]=" + name);
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet [age]=" + this.age + " [name]=" + name);
}
}
BeanPostProcessor类:
package com.ws.spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("MyBeanPostProcessor postProcessAfterInitialization beanName : " +beanName);
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("MyBeanPostProcessor postProcessBeforeInitialization >>> beanName : " +beanName);
return bean;
}
}
配置xml :
<bean id="user" class="com.ws.model.User" init-method="initMethod">
<property name="age" value="${age}"></property>
<property name="name" value="${name}"></property>
</bean>
User 构造器
set 注入
MyBeanPostProcessor postProcessBeforeInitialization >>> beanName : user
afterPropertiesSet [age]=192 [name]=ws
[initMethod] [age]=192 [name]=ws
MyBeanPostProcessor postProcessAfterInitialization beanName : user