我刚开始学春天。在实现一个示例程序时,我遇到了一个问题,并想在这个论坛上查看以获得答案。
下面是spring.xml
<?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());
}
我的客户 bean:
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;
}
}
问题1:因为我的spring.xml 有大约4 个bean 的配置。但是只有三个 bean 的输出(customerDAO 除外)。为什么?
问题2:如果我只想为 customerDAO 调用之前和之后的流程初始化方法怎么办?可能就这么简单?我不知道。但请回答。提前致谢
输出:
IN:postProcessBeforeInitialization IN:postProcessAfterInitialization - bean 初始化类 org.springdemo.Triangle IN:postProcessBeforeInitialization IN:postProcessAfterInitialization - bean 初始化类 org.springdemo.emp.Address IN:postProcessBeforeInitialization IN:postProcessAfterInitialization - bean 初始化类 org.springdemo.emp.Employee customerDAO