gpt4 book ai didi

java - Spring BeanPostProcessor 被调用了 3 次

转载 作者:行者123 更新时间:2023-11-29 04:39:29 27 4
gpt4 key购买 nike

我正在执行 BeanPostProcessor 实现。我的 Bean 后处理器执行了 3 次。我在 init 方法之前额外调用了 2 次后处理器。我无法找到它发生的原因。请帮助我。

我的代码和配置文件如下

BeanPostProcessor 实现

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 方法----初始化后----..设置名称.......getName......名字是..测试用户

最佳答案

Plain bean factories allow for programmatic registration of post-processors, applying to all beans created through this factory.

http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/config/BeanPostProcessor.html

您已经定义了 3 个 bean,AppConfig、customer 和 PP。 bean 后处理器将在每次创建 bean 后执行。如果你有 3 个 bean,它将被执行 3 次。

@Configuration
public class AppConfig {
@Bean(name="customer")
public Customer getCustomer(){
return new Customer();
}
@Bean
public BeanPP getPP(){
return new BeanPP();
}
}

@Configuration也定义了一个bean,因为它继承自@Component。

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html

关于java - Spring BeanPostProcessor 被调用了 3 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39832589/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com