您能否告诉我如何使用Spring Javaconfig直接将属性文件加载/自动装配到java.util.Properties字段?
谢谢!
稍后编辑 - 仍在寻找答案: 是否可以使用Spring JavaConfig将属性文件直接加载到java.util.Properties字段中?
您能否告诉我如何使用Spring Javaconfig直接将属性文件加载/自动装配到java.util.Properties字段?
谢谢!
稍后编辑 - 仍在寻找答案: 是否可以使用Spring JavaConfig将属性文件直接加载到java.util.Properties字段中?
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")
使用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");
...
}
我没有看到将它们直接注入Java.util.properties的方法。但是您可以创建一个使用此注释作为包装器的类,并以这种方式构建属性。
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")
使用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");
...
}
我没有看到将它们直接注入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配置非常简单,如上所示。
还有这种方法可以直接使用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 MyConfig {
@Bean
public Properties myPropertyBean() {
Properties properties = new Properties();
properties.load(...);
return 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
领域。