Spring-BeanPostProcessor接口
我刚开始学春天。在执行一个示例程序时,我遇到了一个问题,并考虑在这个论坛中查看以获得答案 下面是spring.xml 我的客户bean: 问题1:因为我的spring.xml有4个bean的配置。但输出仅针对三个bean(customerDAO除外)。为什么? 问题2:如果我只想为customerDAO调用进程初始化前后的方法,该怎么办? 可能这么简单?我不确定。但请回答。提前谢谢 输出: IN:初始化前的后处理 在:postProcessAfterInitialization-bean initializedclass org.springdemo.Triangle中 IN:初始化前的后处理 IN:postProcessAfterInitialization-bean initializedclass org.springdemo.emp.Address IN:初始化前的后处理 IN:postProcessAfterInitialization-bean initializedclass org.springdemo.emp.EmployeeSpring-BeanPostProcessor接口,spring,Spring,我刚开始学春天。在执行一个示例程序时,我遇到了一个问题,并考虑在这个论坛中查看以获得答案 下面是spring.xml 我的客户bean: 问题1:因为我的spring.xml有4个bean的配置。但输出仅针对三个bean(customerDAO除外)。为什么? 问题2:如果我只想为customerDAO调用进程初始化前后的方法,该怎么办? 可能这么简单?我不确定。但请回答。提前谢谢 输出: IN:初始化前的后处理 在:postProcessAfterInitialization-bean ini
customerDAOBeanPostProcessor的目的是拦截其他bean的初始化。它无法截获自己的初始化,因为Spring保证在调用其后处理方法时后处理器完全初始化 如果在初始化这个bean之后需要执行操作,可以执行以下操作之一:
- 实现
并重写初始化bean
AfterPropertieSet
- 使用
的
属性指定要调用的方法的名称init method
- 用
@PostConstruct
- 实现
并重写初始化bean
AfterPropertieSet
- 使用
的
属性指定要调用的方法的名称init method
- 用
@PostConstruct
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org /dtd/spring-beans-2.0.dtd">
<beans>
<bean id="triangle" class="org.springdemo.Triangle" autowire="byName">
</bean>
<bean id="employee" class="org.springdemo.emp.Employee" autowire="byName">
</bean>
<bean id="address" class="org.springdemo.emp.Address">
<property name="city" value="PUNE"></property>
<property name="street" value="MH"></property>
<property name="pin" value="411013"></property>
</bean>
<bean id="customerDAO" class="org.mykong.springdb.Customer">
</bean>
</beans>
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
Customer customer = (Customer) context.getBean("customerDAO");
System.out.println(customer.getBeanName());
}
public class Customer implements BeanNameAware, BeanPostProcessor{
private String name;
private int age;
protected Customer() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "Customer id : " + " , Name : " + this.name + " , Age: " + this.age;
}
public void setBeanFactory(BeanFactory arg0) throws BeansException {
}
private String beanName = null;
public void setBeanName(String name) {
this.beanName = name;
}
public String getBeanName() {
return beanName;
}
public Object postProcessAfterInitialization(Object bean, String arg1)
throws BeansException {
System.out.println(" IN : postProcessAfterInitialization - bean initialized" + bean.getClass() );
return bean;
}
public Object postProcessBeforeInitialization(Object bean, String arg1)
throws BeansException {
System.out.println(" IN : postProcessBeforeInitialization " );
return bean;
}
}