16


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

谢谢!

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

4

6 回答 6

12

XML基础方式:

在春季配置中:

<util:properties id="myProperties" location="classpath:com/foo/my-production.properties"/>

在你的课堂上:

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

仅限 JavaConfig

好像有注解:

@PropertySource("classpath:com/foo/my-production.properties")

用这个注释一个类会将文件中的属性加载到环境中。然后,您必须将 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");
    ...
}

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

于 2013-03-13T15:03:21.743 回答
5

声明一个PropertiesFactoryBean.

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

旧代码具有以下配置

<bean id="mailConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="location" value="classpath:mail.properties"/>
</bean>

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

于 2015-09-30T10:07:15.147 回答
2

这是一个古老的主题,但也有一个更基本的解决方案。

@Configuration
public class MyConfig {
    @Bean
    public Properties myPropertyBean() {
        Properties properties = new Properties();
        properties.load(...);
        return properties;
    }
}
于 2014-12-29T13:08:19.733 回答
1

还有这种方法可以直接使用 xml 配置注入属性。上下文 xml 有这个

<util:properties id="myProps" location="classpath:META-INF/spring/conf/myProps.properties"/>

而java类只是使用

@javax.annotation.Resource
private Properties myProps;

瞧!!它加载。Spring 使用 xml 中的 'id' 属性绑定到代码中的变量名称。

于 2013-10-01T12:23:32.167 回答
1

你可以试试这个

@Configuration  
public class PropertyConfig { 

 @Bean("mailProperties")  
 @ConfigurationProperties(prefix = "mail")   
  public Properties getProperties() {
     return new Properties();  
  }

}

确保在 application.properties 中定义属性

于 2021-02-01T12:22:50.633 回答
0

应用程序.yml

root-something:
    my-properties:
        key1: val1
        key2: val2

您的类型安全 pojo:

import java.util.Properties;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "root-something")
public class RootSomethingPojo {

    private Properties myProperties;

您的容器配置:

@Configuration
@EnableConfigurationProperties({ RootSomethingPojo .class })
public class MySpringConfiguration {

这会将键值对直接注入到myProperties字段中。

于 2017-03-30T09:53:45.613 回答