我只需要在类menu.properties中读取MyServiceImpl.java文件,这些值不是特定于环境的。
menu.properties
----------------
menu.option=option1,option2,option31)使用@PropertySource
@Configuration
@ComponentScan(basePackages = { "com.test.*" })
@PropertySource("classpath:menu.properties")
public class MyServiceImpl{
@Autowired
private Environment env;
public List<String> createMenu(){
String menuItems = env.getProperty("menu.option");
...}
}2)如何在MyServiceImpl.java中访问下面的bean
<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:menu.properties"/>
</bean>我需要遵循哪种方法,PropertiesFactoryBean和PropertySource有什么区别?
发布于 2015-04-17 00:19:32
使用环境:环境为提供属性源提供了方便的接口。这些属性可以从jvm args、系统变量、属性文件等中加载。使用env提供了更好的抽象IMHO。
如果有选择,我更喜欢Environment,因为它提供了更好的抽象。与明天可以从jvm参数或系统变量加载的属性文件不同,接口将保持不变。
回答你的第二个问题(我也提供了简短的表格)。
长表:
<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:menu.properties"/>
</bean>简写:
<util:properties id="properties" location="classpath:menu.properties"/>
public class MyServiceImpl{
@Autowired
private Properties properties;
public List<String> createMenu(){
String menuItems = properties.getProperty("menu.option");
...}
}第三选择
如果要直接读取属性,如果没有特定于环境的属性,我建议使用注册<context:property-placeholder>的PropertySourcesPlaceholderConfigurer。
<context:property-placeholder location="classpath:menu.properties" />如果您如上声明,您可以使用@value注释直接读取以下值。
public class MyServiceImpl{
@value("${menu.option}")
String menuItems;
public List<String> createMenu(){
//use items directly;
...}
}https://stackoverflow.com/questions/29680894
复制相似问题