Весенняя конфигурация Java | Как получить IndexedArgumentsValue из BeanDefinition

Рассмотрим следующий пример:

Класс конфигурации

@Configuration открытый класс MyTestConfig {

@Value("${const.arg.a}") String constArgA;
@Value("${const.arg.b}") String constArgB;

@Bean
public static PropertyPlaceholderConfigurer properties(){
    SystemPropertyPlaceholderConfigurer propertyConfigurer = new SystemPropertyPlaceholderConfigurer();
    propertyConfigurer.setLocation( "test.properties" );
    propertyConfigurer.setPropertyPrefixValue("TEST");
    propertyConfigurer.setIgnoreUnresolvablePlaceholders( true );
    return propertyConfigurer;
}

@Bean
public SpringTest springTest(){
    return new SpringTest(constArgA, constArgB);

}

}


Бин

открытый класс SpringTest {

private String constArgA;
private String constArgB;

public SpringTest(String constArgA, String constArgB){
    this.constArgA = constArgA;
    this.constArgB = constArgB;

    System.out.println("constArgA " + constArgA);
    System.out.println("constArgB " + constArgB);
}

public void sayHello(){
    System.out.println("Hello, I hope this works");
    System.out.println("constArgA " + constArgA);
    System.out.println("constArgB " +  constArgB);
}

}


SystemPropertyPlaceholderConfigurer является расширением PropertyPlaceholderConfigurer, в котором мы пытаемся манипулировать некоторыми аргументами Bean Constructor.

В моем случае мне нужно получить доступ к аргументам конструктора, но я вижу пустой список, если я получаю BeanDefinition от ConfigurableListableBeanFactory.

Чтобы быть точным, все следующее для Bean SpringTest пусто:

beanDefinition.getPropertyValues();
beanDefinition.getConstructorArgumentValues().getIndexedArgumentValues();
beanDefinition.getConstructorArgumentValues().getGenericArgumentValues();

Я ожидаю получить constArgA и constArgB в ConstructorArgumentValues.

Теперь, если я заменю конфигурацию на основе Java на конфигурацию на основе Xml следующим образом:


<?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-2.0.xsd">

<bean
    class="com.abc.SystemPropertyPlaceholderConfigurer">
    <property name="location">
        <value>test.properties</value>
    </property>
    <property name="propertyPrefixValue">
        <value>TEST</value>
    </property>
</bean>


<bean id="springTest" class="com.abc.SpringTest" >
    <constructor-arg index="0" type="java.lang.String" value="${const.arg.a}" />
    <constructor-arg index="1" type="java.lang.String" value="${const.arg.b}" />        
</bean>
</beans>

Теперь, если я попытаюсь получить доступ к моему BeanDefinition, я получу 2 аргумента конструктора в:

beanDefinition.getConstructorArgumentValues().getIndexedArgumentValues()

Не могли бы вы помочь мне понять, в чем разница между этими двумя способами конфигурации, и если я хочу использовать конфигурацию на основе Java, как мне получить доступ к аргументам конструктора в моих bean-компонентах? В основном мне нужно ввести свои свойства из файла свойств в качестве аргументов конструктора и выполнить некоторую обработку с помощью моей реализации PropertyPlaceholderConfigurer.


person madhulika    schedule 11.12.2014    source источник


Ответы (1)


В классе @configuration я обычно делаю так

@Configuration
@PropertySource("classpath:/test.properties")
public class MyTestConfig {

    @Resource
    private Environment env;

    @Bean
    public SpringTest springTest(){
        return new SpringTest(env.getRequiredProperty("const.arg.a"), env.getRequiredProperty("const.arg.b"));

    }
}
person wesker317    schedule 11.12.2014
comment
Спасибо за ваш ответ, но я пытаюсь понять, почему следующее ничего не возвращает мне для моего Bean 'SpringTest': BeanDefinition beanDefinition = configurableListableBeanFactory.getBean(SpringTest.class); beanDefinition.getPropertyValues(); beanDefinition.getConstructorArgumentValues().getIndexedArgumentValues(); beanDefinition.getConstructorArgumentValues().getGenericArgumentValues(); Аргументы конструктора в bean-компоненте возвращают пустой список, если я использую конфигурацию на основе Java, но возвращают 2 аргумента, если я использую конфигурацию на основе xml. - person madhulika; 12.12.2014