Why is BeanDefinition.getPropertyValues ​​returning an empty list

I have configured spring with AnnotationConfigApplicationContext

. Although I named BeanDefinition.getPropertyValues()

in implementation BeanFactoryPostProcessor

, I got an empty list. But if I configured spring with ClasspathXmlApplicationContext

it will return the correct value. Does anyone know the reason?

Here are my codes:

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

      

Many thanks.

+3


source to share


1 answer


You have a null list, simply because it BeanFactoryPostProcessor

is called before instantiation and assigned values. They will be called prior to instantiation.

I did exactly what you were trying to do using a different interface. Use the interface 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;
    }
}

      

0


source







All Articles