【发布时间】:2017-02-11 10:56:52
【问题描述】:
我正在做一个 BeanPostProcessor 实现。我的 Bean PostProcessor 执行了 3 次。我在 init 方法之前额外调用了 2 次后处理器。我无法找到它发生的原因。请帮帮我。
我的代码和配置文件如下
BeanPostProcesssor 实现
public class BeanPP implements BeanPostProcessor{
@Override
public Object postProcessBeforeInitialization(Object o, String string) throws BeansException {
System.out.println("---before initialization ------");
return o;
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object postProcessAfterInitialization(Object o, String string) throws BeansException {
System.out.println("----After initializaion ---- ");
return o;
//To change body of generated methods, choose Tools | Templates.
}
}
客户 Bean
public class Customer {
private String name;
public String getName() {
System.out.println("..getName.....");
return name;
}
public void setName(String name) {
System.out.println("..setName.....");
this.name = name;
}
@PostConstruct
public void init(){
System.out.println("....Bean is going though init method");
}
@PreDestroy
public void destory(){
System.out.println("....Bean is going to destroy.......");
}
}
配置类
@Configuration
public class AppConfig {
@Bean(name="customer")
public Customer getCustomer(){
return new Customer();
}
@Bean
public BeanPP getPP(){
return new BeanPP();
}
}
主类
public class MainApp {
public static void main(String[] args) {
ApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.class);
Customer customer = (Customer)appContext.getBean("customer");
customer.setName("test user ");
System.out.println(".Name is .."+customer.getName());
}
}
输出
---初始化前------ ----初始化后---- ---初始化前 ------ ----初始化后---- ---初始化前 ------ ....Bean 正在使用 init 方法 ----初始化后---- ..设置名称..... ..获取名称..... .Name 是 ..test 用户
【问题讨论】:
-
你有 3 个 bean,它会为所有它们调用。你有
AppConfig、Customer和BeanPP,这三个都是豆子。