日期:2014-05-18 浏览次数:20636 次
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean class="com.fu.model.MyBeanPostProcessor"/>
<bean id="user" class="com.fu.model.User" init-method="init">
<property name="userName">
<value>xiaogou</value>
</property>
</bean>
</beans>
import org.springframework.beans.factory.InitializingBean;
public class User implements InitializingBean
{
private String userName;
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName= userName;
}
@Override
public void afterPropertiesSet() throws Exception
{
// TODO Auto-generated method stub
System.out.println("正在执行初始化方法afterPropertiesSet......");
}
public void init(){
System.out.println("正在执行初始化方法 init.....");
}
}
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBeanPostProcessor implements BeanPostProcessor
{
@Override
public Object postProcessAfterInitialization(Object arg0, String arg1)
throws BeansException
{
System.out.println(arg1+"初始化后......");
return null;
}
@Override
public Object postProcessBeforeInitialization(Object arg0, String arg1)
throws BeansException
{
System.out.println(arg1+"初始化前......");
return null;
}
}
public class SpringTest
{
public static void main(String[] args) throws FileNotFoundException
{
/**
* BeanFactory和ApplicationContext对待bean后置处理器稍有不同。
* ApplicationContext会自动检测在配置文件中实现了BeanPostProcessor接口的所有bean,
* 并把它们注册为后置处理器,然后在容器创建bean的适当时候调用它。
* 部署一个后置处理器同部署其他的bean并没有什么区别。
* 而使用BeanFactory实现的时候,bean 后置处理器必须通过下面类似的代码显式地去注册:
*/
ClassPathXmlApplicationContext ctx =new ClassPathXmlApplicationContext("applicationContext.xml");
User u=(User)ctx.getBean("user");
System.out.println(u);
}
@Override
public Object postProcessAfterInitialization(Object arg0, String&nb