请考虑以下示例:
配置类
@配置公共类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构造器参数。
对于我的用例,我需要访问构造函数参数,但是如果我从BeanDefinition获得ConfigurableListableBeanFactory,我会看到一个空列表。
准确地说,Bean 'SpringTest‘的以下所有内容都是空的:
beanDefinition.getPropertyValues();
beanDefinition.getConstructorArgumentValues().getIndexedArgumentValues();
beanDefinition.getConstructorArgumentValues().getGenericArgumentValues();我希望在constArgA中接收到constArgB和ConstructorArgumentValues。
现在,如果我将基于Java的Config替换为基于Xml的Config,如下所示:
<?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,我会在以下两个构造函数参数中获得:
beanDefinition.getConstructorArgumentValues().getIndexedArgumentValues()
请您帮助我理解这两种配置方式的区别,如果我想使用基于Java的Config,如何访问bean上的构造函数参数?基本上,我需要将属性文件中的属性作为构造函数参数注入,并需要通过PropertyPlaceholderConfigurer的实现对其执行一些处理。
发布于 2014-12-11 13:54:44
在@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"));
}
}https://stackoverflow.com/questions/27421942
复制相似问题