用于java.util.Properties字段的Spring JavaConfig

Rox*_*ana 14 spring inject


您能否告诉我如何使用Spring Javaconfig直接将属性文件加载/自动装配到java.util.Properties字段?

谢谢!

稍后编辑 - 仍然在寻找答案: 是否可以使用Spring JavaConfig将属性文件直接加载到java.util.Properties字段中?

jac*_*ted 8

XML基础方式:

在春季配置:

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

在你班上:

@Autowired
@Qualifier("myProperties")
private Properties myProperties;
Run Code Online (Sandbox Code Playgroud)

仅限JavaConfig

看起来有一个注释:

@PropertySource("classpath:com/foo/my-production.properties")
Run Code Online (Sandbox Code Playgroud)

使用this注释类会将文件中的属性加载到Environment中.然后,您必须将环境自动装配到类中以获取属性.

@Configuration
@PropertySource("classpath:com/foo/my-production.properties")
public class AppConfig {

@Autowired
private Environment env;

public void someMethod() {
    String prop = env.getProperty("my.prop.name");
    ...
}
Run Code Online (Sandbox Code Playgroud)

我没有看到将它们直接注入Java.util.properties的方法.但是您可以创建一个使用此注释作为包装器的类,并以这种方式构建属性.


sid*_*ate 6

声明一个PropertiesFactoryBean.

@Bean
public PropertiesFactoryBean mailProperties() {
    PropertiesFactoryBean bean = new PropertiesFactoryBean();
    bean.setLocation(new ClassPathResource("mail.properties"));
    return bean;
}
Run Code Online (Sandbox Code Playgroud)

遗留代码具有以下配置

<bean id="mailConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="classpath:mail.properties"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

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