我有一个包含很多值的属性文件,我不想在我的 bean-configuration-file 中单独列出它们。例如:
<property name="foo">
<value>${foo}</value>
</property>
<property name="bar">
<value>${bar}</value>
</property>
等等。
我想像java.util.Properties
. java.util.Map
有没有办法这样做?
我有一个包含很多值的属性文件,我不想在我的 bean-configuration-file 中单独列出它们。例如:
<property name="foo">
<value>${foo}</value>
</property>
<property name="bar">
<value>${bar}</value>
</property>
等等。
我想像java.util.Properties
. java.util.Map
有没有办法这样做?
对于 Java 配置,您可以使用如下内容:
@Autowired @Qualifier("myProperties")
private Properties myProps;
@Bean(name="myProperties")
public Properties getMyProperties() throws IOException {
return PropertiesLoaderUtils.loadProperties(
new ClassPathResource("/myProperties.properties"));
}
如果您Qualifier
为每个实例分配一个唯一的 bean 名称 (),您也可以通过这种方式拥有多个属性。
是的,您可以使用<util:properties>
加载属性文件并将生成的java.util.Properties
对象声明为 bean。然后,您可以像注入任何其他 bean 属性一样注入它。
请参阅Spring 手册的 C.2.2.3 部分及其示例:
<util:properties id="myProps" location="classpath:com/foo/jdbc-production.properties"
请记住util:
按照这些说明声明命名空间。
对于 Java 配置,使用PropertiesFactoryBean
:
@Bean
public Properties myProperties() {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/myProperties.properties"));
Properties properties = null;
try {
propertiesFactoryBean.afterPropertiesSet();
properties = propertiesFactoryBean.getObject();
} catch (IOException e) {
log.warn("Cannot load properties file.");
}
return properties;
}
然后,设置属性对象:
@Bean
public AnotherBean myBean() {
AnotherBean myBean = new AnotherBean();
...
myBean.setProperties(myProperties());
...
}
希望这对那些对 Java Config 方式感兴趣的人有所帮助。
机制是可能的PropertyOverrideConfigurer
:
<context:property-override location="classpath:override.properties"/>
属性文件:
beanname1.foo=foovalue
beanname2.bar.baz=bazvalue
这是@skaffman在这个 SO question 中的回应的回声。当我将来尝试解决这个问题时,我会添加更多细节来帮助他人和我自己。
注入属性文件的三种方式
<bean id="myProps" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:com/foo/jdbc-production.properties</value>
</list>
</property>
</bean>
参考(链接)
<?xml version="1.0" encoding="UTF-8"?>
<beans
...
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="...
...
http://www.springframework.org/schema/util/spring-util.xsd"/>
<util:properties id="myProps" location="classpath:com/foo/jdbc-production.properties"/>
参考(链接)
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:com/foo/jdbc-production.properties" />
</bean>
参考(链接)
本质上,所有方法都可以Properties
从属性文件中创建一个 bean。您甚至可以使用注入器直接从属性文件中注入一个@Value
值
@Value("#{myProps[myPropName]}")
private String myField;