我有一个单独的配置类,我想存储为我们的Web应用程序的所有属性。
我们如何在application.properties文件中读取像任何其他属性文件,而无需使用注解?
什么是对application.properties鼻内完全合格的文件名/application.properties?
我们只想读一次application.properties。
春天已经启动读取存储在application.properties
的所有属性和更多,请阅读Externalized Configuration文档。
如果你想映射一个属性命名server.port
你可以只使用@Value("${server.port}") Integer port
。
如果您想获得由Spring引导加载的所有属性,可以使用Environment
对象,并访问所有加载PropertySources
,并从每个属性源中检索的所有值。
在这本answer显示如何。然而,为了避免失去加载性能的优先顺序,你必须扭转属性源列表。在这里你可以找到的代码加载所有属性不失春天优先顺序:
@Configuration
public class AppConfiguration {
@Autowired
Environment env;
public void loadProperties() {
Map<String, Object> map = new HashMap();
for (Iterator it = ((AbstractEnvironment) env).getPropertySources().iterator().reverse(); it.hasNext(); ) {
PropertySource propertySource = (PropertySource) it.next();
if (propertySource instanceof MapPropertySource) {
map.putAll(((MapPropertySource) propertySource).getSource());
}
}
}
}