我用AnnotationConfigApplicationContext配置了spring。当我在一个BeanDefinition.getPropertyValues()实现中调用BeanFactoryPostProcessor时,我得到了一个空列表。但是,如果我用ClasspathXmlApplicationContext配置spring,它将返回正确的值。有人知道原因吗?
这是我的密码:
@Configuration
public class AppConfig {
@Bean
public BeanFactoryPostProcessorTest beanFactoryPostProcessorTest(){
return new BeanFactoryPostProcessorTest();
}
@Bean
public Person person(){
Person person = new Person();
person.setName("name");
person.setAge(18);
return person;
}
}public class BeanFactoryPostProcessorTest implements BeanFactoryPostProcessor{
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
BeanDefinition bd = beanFactory.getBeanDefinition("person");
MutablePropertyValues propertyValues = bd.getPropertyValues();
if(propertyValues.contains("name")){
propertyValues.addPropertyValue("name","zhangfei");
}
System.out.println("Factory modfy zhangfei");
}
}public class MainClass {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
/*ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("context.xml");*/
Person person = context.getBean(Person.class);
System.out.println(person.getName());
}
}非常感谢。
发布于 2015-04-22 05:52:40
只因为在实例创建和赋值之前调用了BeanFactoryPostProcessor,您就得到了一个空列表。它们将在实例创建之前被调用。
我已经做了同样的事情,你试图用不同的界面。使用BeanPostProcessor接口。
public class BeanPostProcessorTest implements BeanPostProcessor{
@Override
public Object postProcessAfterInitialization(Object bean, String name)
throws BeansException {
if("person".equals(name)){
Person person =((Person)bean);
if("name".equals(person.getName())){
person.setName("zhangfei");
}
return person;
}
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object arg0, String arg1)
throws BeansException {
return arg0;
}
}https://stackoverflow.com/questions/29787132
复制相似问题