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

Jan*_*Jan 10 resources spring properties-file

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

<property name="foo">
    <value>${foo}</value>
</property>
<property name="bar">
    <value>${bar}</value>
</property>
Run Code Online (Sandbox Code Playgroud)

等等.

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

rus*_*tyx 17

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

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

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

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


ska*_*man 14

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

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

<util:properties id="myProps" location="classpath:com/foo/jdbc-production.properties"
Run Code Online (Sandbox Code Playgroud)

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


jel*_*ies 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;
}
Run Code Online (Sandbox Code Playgroud)

然后,设置属性对象:

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

    myBean.setProperties(myProperties());

    ...
}
Run Code Online (Sandbox Code Playgroud)

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