【发布时间】:2013-03-01 12:05:46
【问题描述】:
您能告诉我如何使用 Spring Javaconfig 直接将属性文件加载/自动装配到 java.util.Properties 字段吗?
谢谢!
稍后编辑 - 仍在寻找答案: 是否可以使用 Spring JavaConfig 将属性文件直接加载到 java.util.Properties 字段中?
【问题讨论】:
标签: java spring spring-boot inject
您能告诉我如何使用 Spring Javaconfig 直接将属性文件加载/自动装配到 java.util.Properties 字段吗?
谢谢!
稍后编辑 - 仍在寻找答案: 是否可以使用 Spring JavaConfig 将属性文件直接加载到 java.util.Properties 字段中?
【问题讨论】:
标签: java spring spring-boot inject
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 的方法。但是您可以创建一个使用此注释的类,该注释充当包装器,并以这种方式构建属性。
【讨论】:
声明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 配置非常简单。
【讨论】:
这是一个古老的主题,但也有一个更基本的解决方案。
@Configuration
public class MyConfig {
@Bean
public Properties myPropertyBean() {
Properties properties = new Properties();
properties.load(...);
return properties;
}
}
【讨论】:
还有这种方法可以直接使用 xml 配置注入属性。上下文 xml 有这个
<util:properties id="myProps" location="classpath:META-INF/spring/conf/myProps.properties"/>
而java类只使用
@javax.annotation.Resource
private Properties myProps;
瞧!!它加载。 Spring 使用 xml 中的 'id' 属性来绑定代码中的变量名。
【讨论】:
你可以试试这个
@Configuration
public class PropertyConfig {
@Bean("mailProperties")
@ConfigurationProperties(prefix = "mail")
public Properties getProperties() {
return new Properties();
}
}
确保在 application.properties 中定义属性
【讨论】:
application.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 字段。
【讨论】: