如何在springbean中注入完整的属性文件

时间:2011-05-09 15:04:54

标签: spring resources properties-file

我有一个包含很多值的属性文件,我不想单独列在我的bean-configuration文件中。 E.g:

<property name="foo">
    <value>${foo}</value>
</property>
<property name="bar">
    <value>${bar}</value>
</property>

等等。

我想将java.util.Properties或更少的全部注入java.util.Map。 有办法吗?

5 个答案:

答案 0 :(得分:16)

对于Java配置,您可以使用以下内容:

var validVar;

try {
    validVar = invalidVar;
} catch (e) {}

functionToCall(validVar);

如果为每个实例分配一个唯一的bean名称(@Autowired @Qualifier("myProperties") private Properties myProps; @Bean(name="myProperties") public Properties getMyProperties() throws IOException { return PropertiesLoaderUtils.loadProperties( new ClassPathResource("/myProperties.properties")); } ),也可以通过这种方式拥有多个属性。

答案 1 :(得分:14)

是的,您可以使用<util:properties>加载属性文件并将生成的java.util.Properties对象声明为bean。然后,您可以像任何其他bean属性一样注入它。

请参阅section C.2.2.3 of the Spring manual及其示例:

<util:properties id="myProps" location="classpath:com/foo/jdbc-production.properties"

请记住按照these instructions声明util:命名空间。

答案 2 :(得分:11)

对于Java Config,请使用PropertiesFactoryBean

@Bean
public Properties myProperties() {
    PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
    propertiesFactoryBean.setLocation(new ClassPathResource("/myProperties.properties"));
    Properties properties = null;
    try {
        propertiesFactoryBean.afterPropertiesSet();
        properties = propertiesFactoryBean.getObject();

    } catch (IOException e) {
        log.warn("Cannot load properties file.");
    }
    return properties;
}

然后,设置属性对象:

@Bean
public AnotherBean myBean() {
    AnotherBean myBean = new AnotherBean();
    ...

    myBean.setProperties(myProperties());

    ...
}

希望这对那些对Java Config方式感兴趣的人有所帮助。

答案 3 :(得分:2)

可以使用PropertyOverrideConfigurer机制:

<context:property-override location="classpath:override.properties"/>

属性文件:

beanname1.foo=foovalue
beanname2.bar.baz=bazvalue

该机制在3.8.2.2 Example: the PropertyOverrideConfigurer

部分进行了解释

答案 4 :(得分:0)

这是@skaffman在这个SO问题中的回应。将来尝试解决此问题时,我会添加更多详细信息,以帮助其他人和我自己。

有三种方法可以插入属性文件

方法1

<bean id="myProps" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath:com/foo/jdbc-production.properties</value>
        </list>
    </property>
</bean>

参考(link

方法2

<?xml version="1.0" encoding="UTF-8"?>
<beans
    ...
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="...
    ...
    http://www.springframework.org/schema/util/spring-util.xsd"/>
    <util:properties id="myProps" location="classpath:com/foo/jdbc-production.properties"/>

参考(link

方法3

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:com/foo/jdbc-production.properties" />
</bean>

参考(link

基本上,所有方法都可以从属性文件中创建一个Properties bean。您甚至可以使用@Value注入器

直接从属性文件中注入值
@Value("#{myProps[myPropName]}")
private String myField;