10

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

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

等等。

我想像java.util.Properties. java.util.Map有没有办法这样做?

4

5 回答 5

18

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

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

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

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

于 2015-07-02T20:01:29.473 回答
14

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

请参阅Spring 手册的 C.2.2.3 部分及其示例:

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

请记住util:按照这些说明声明命名空间。

于 2011-05-09T15:20:30.997 回答
11

对于 Java 配置,使用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 方式感兴趣的人有所帮助。

于 2013-03-04T15:08:02.947 回答
2

机制是可能的PropertyOverrideConfigurer

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

属性文件:

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

该机制在第3.8.2.2 节中进行了解释示例:PropertyOverrideConfigurer

于 2011-05-09T15:21:26.457 回答
0

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

注入属性文件的三种方式

方法一

<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>

参考(链接

方法二

<?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"/>

参考(链接

方法三

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

参考(链接

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

@Value("#{myProps[myPropName]}")
private String myField; 
于 2019-02-15T17:01:07.737 回答