2011-05-09 61 views
10

我有一个包含很多值的属性文件,我不想单独列出它们到我的bean配置文件中。例如:如何在Springbean中注入完整的属性文件

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

等等。

我想完全注入为java.util.Properties或更少作为java.util.Map。 有没有办法做到这一点?

回答

13

是的,您可以使用<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

+0

我会试试这个 - 谢谢!!! – Jan 2011-05-09 15:41:35

+4

如何在代码中访问它? – Sridhar 2015-03-05 05:38:47

2

有可能与PropertyOverrideConfigurer机制:

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

属性文件:

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

的机制在部分3.8.2.2 Example: the PropertyOverrideConfigurer

+0

感谢您的回答 - 我的错,属性文件将由“非开发者”编辑,并且对于没有特殊背景的编辑者来说应该是“易于阅读”的。因此,豆的名字并不是用作关键的正确方法。 – Jan 2011-05-09 15:41:10

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的配置方式。

+0

哇,这是很多代码。没有一种简单的方法,像1-liner XML配置''? – rustyx 2015-07-02 19:30:53

+0

@rustyx哦!我当时没有找到任何其他方式来做到这一点,但[你的](http://stackoverflow.com/a/31193653/787375)非常好! :) – jelies 2016-01-21 13:21:25

14

对于Java的配置,你可以使用这样的事情:

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

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

你也可以有多个属性这样,如果你分配一个唯一的bean名称(Qualifier)到每个实例。

相关问题