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

问题描述 投票:10回答:5

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

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

等等。

我想将所有完全注入java.util.Properties或更少作为java.util.Map。有办法吗?

spring resources properties-file
5个回答
16
投票

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

@Autowired @Qualifier("myProperties")
private Properties myProps;

@Bean(name="myProperties")
public Properties getMyProperties() throws IOException {
    return PropertiesLoaderUtils.loadProperties(
        new ClassPathResource("/myProperties.properties"));
}

如果为每个实例分配一个唯一的bean名称(Qualifier),也可以通过这种方式拥有多个属性。


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"

记得根据util:声明these instructions名称空间。


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方式感兴趣的人有所帮助。


2
投票

使用PropertyOverrideConfigurer机制是可能的:

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

属性文件:

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

该机制在3.8.2.2 Example: the PropertyOverrideConfigurer部分进行了解释


0
投票

这是@skaffman在这个SO问题中的回应的回声。当我试图在将来解决这个问题时,我正在添加更多细节来帮助他人和我自己。

注入属性文件有三种方法

Method 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

Method 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

Method 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; 
© www.soinside.com 2019 - 2024. All rights reserved.