4

我用AnnotationConfigApplicationContext. 当我调用BeanDefinition.getPropertyValues()一个BeanFactoryPostProcessor实现时,我得到了一个空列表。但是如果我用 配置了 spring ClasspathXmlApplicationContext,它会返回正确的值。有谁知道原因?

这是我的代码:

@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());
    }
}

非常感谢。

4

1 回答 1

0

您得到一个空列表仅仅是因为在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;
    }
}
于 2015-04-22T05:52:40.257 回答