Java 在Spring中从属性文件中获取值的最佳方法是什么?
我使用以下方法从属性中获取值。但是我想知道哪一个是遵循编码标准的最佳选择?另外,还有其他方法可以从Spring中的属性文件中获取值吗Java 在Spring中从属性文件中获取值的最佳方法是什么?,java,spring,Java,Spring,我使用以下方法从属性中获取值。但是我想知道哪一个是遵循编码标准的最佳选择?另外,还有其他方法可以从Spring中的属性文件中获取值吗 PropertySourcesPlaceholderConfigurer getEnvironment() from the Spring's Application Context Spring EL @Value 与其他配置类(ApplicationConfiguration等)一起,我使用annotation@Service创建了一个类,在这里,我有以下
PropertySourcesPlaceholderConfigurer
getEnvironment() from the Spring's Application Context
Spring EL @Value
与其他配置类(ApplicationConfiguration等)一起,我使用annotation@Service创建了一个类,在这里,我有以下字段来访问文件中的属性:
@Service
public class Properties (){
@Value("${com.something.user.property}")
private String property;
public String getProperty (){ return this.property; }
}
然后我可以自动连接该类并从属性文件中获取属性。Value将是一种简单易用的方法,因为它会将属性文件中的值注入到字段中 Spring 3.1中添加的旧的PropertyPlaceHolderConfigure和新的PropertySourcesplacePlaceHolderConfigurer都解析bean定义属性值和@Value注释中的${…}占位符 与getEnvironment不同 使用属性占位符将不会将属性公开给 Spring环境–这意味着像这样检索值 将不起作用–它将返回null 当您使用
并使用env.getProperty(键)时代码>它将始终返回null
有关使用getEnvironment的问题,请参阅本文:
此外,在Spring Boot中,您可以使用@ConfigurationProperties在application.properties中使用分层和类型安全来定义自己的属性。您不需要为每个字段都输入@Value
@ConfigurationProperties(prefix = "database")
public class Database {
String url;
String username;
String password;
// standard getters and setters
}
在application.properties中:
database.url=jdbc:postgresql:/localhost:5432/instance
database.username=foo
database.password=bar
引用自:答案是,
视情况而定
如果属性是配置值,
然后配置一个属性配置器
(下面是SpringXML配置文件的示例)
不需要将配置值群集到一个类中,
但这样做可以更容易地找到值的使用位置
<bean id="propertyConfigurer"
class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath:configuration.properties</value>
<value>classpath:configuration.overrides.properties</value>
</list>
</property>
</bean>
@Value("${some.configuration.value}")
private String someConfigurationValue;