<util:properties> 在基于 java 的 spring 配置中等效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18895839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:01:57  来源:igfitidea点击:

<util:properties> equivalent in java based configuration for spring

javaspring

提问by Yves Nicolas

What would be the equivalent in java based configuration of XML based spring configuration

在基于 Java 的基于 XML 的 spring 配置的配置中的等价物是什么

<util:properties id="mapper"  location="classpath:mapper.properties" />

To then be able to use this specific property object in code like :

然后能够在如下代码中使用这个特定的属性对象:

@Resource(name = "mapper")
private Properties myTranslator;

Looking at the doc, I looked at the

看着文档,我看了看

@PropertySource

annotation but it seems to me that the particular propertyfile will not be able to be accessed individually from the Environment object.

注释,但在我看来,特定的属性文件将无法从 Environment 对象中单独访问。

采纳答案by Sotirios Delimanolis

Very simply, declare a PropertiesFactoryBean.

很简单,声明一个PropertiesFactoryBean.

@Bean(name = "mapper")
public PropertiesFactoryBean mapper() {
    PropertiesFactoryBean bean = new PropertiesFactoryBean();
    bean.setLocation(new ClassPathResource("com/foo/jdbc-production.properties"));
    return bean;
}

In the documentation here, you'll notice that before they made <util:properties>, they used to use a PropertiesFactoryBeanas such

在文档在这里,你会发现,他们作出之前<util:properties>,他们曾经用PropertiesFactoryBean这样

<!-- creates a java.util.Properties instance with values loaded from the supplied location -->
<bean id="jdbcConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="classpath:com/foo/jdbc-production.properties"/>
</bean>

Converting that to Java config is super easy as shown above.

如上所示,将其转换为 Java 配置非常简单。