有多种方法可以实现相同的目标。下面是spring中常用的一些方式-
-
使用 PropertyPlaceholderConfigurer
-
使用 PropertySource
-
使用 ResourceBundleMessageSource
-
使用 PropertiesFactoryBean
还有更多............
假设ds.type 是您的属性文件中的关键。
使用PropertyPlaceholderConfigurer
注册PropertyPlaceholderConfigurer豆-
<context:property-placeholder location="classpath:path/filename.properties"/>
或
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:path/filename.properties" ></property>
</bean>
或
@Configuration
public class SampleConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
//set locations as well.
}
}
注册PropertySourcesPlaceholderConfigurer后可以访问值-
@Value("${ds.type}")private String attr;
使用PropertySource
在最新的spring版本中你不需要注册PropertyPlaceHolderConfigurer和@PropertySource,我找到了一个很好的link来了解版本兼容性-
@PropertySource("classpath:path/filename.properties")
@Component
public class BeanTester {
@Autowired Environment environment;
public void execute() {
String attr = this.environment.getProperty("ds.type");
}
}
使用ResourceBundleMessageSource
注册 Bean-
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:path/filename.properties</value>
</list>
</property>
</bean>
访问价值-
((ApplicationContext)context).getMessage("ds.type", null, null);
或
@Component
public class BeanTester {
@Autowired MessageSource messageSource;
public void execute() {
String attr = this.messageSource.getMessage("ds.type", null, null);
}
}
使用PropertiesFactoryBean
注册 Bean-
<bean id="properties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:path/filename.properties</value>
</list>
</property>
</bean>
将 Properties 实例连接到您的类中-
@Component
public class BeanTester {
@Autowired Properties properties;
public void execute() {
String attr = properties.getProperty("ds.type");
}
}