【发布时间】:2018-01-16 04:38:33
【问题描述】:
我试图在我的 springboot 应用程序中加载一次属性。
实际上,我已经创建了一个类来做到这一点:
@Configuration
@PropertySource(value = { "classpath:parameters.properties", "classpath:iot.properties" })
public class PropertiesHelper {
@Autowired
protected Environment env;
private static Environment properties;
@PostConstruct
public void init() {
properties = env;
}
public static String getProperty(final String propertyName) {
return properties.getProperty(propertyName);
}
}
这个类工作正常,但这不是干净的代码(声纳讨厌我的静态变量)。
那么,我怎样才能在我的 springboot 应用程序中正确加载我的所有属性并且只加载一次?
【问题讨论】:
-
1.为什么? 2. 环境可能不会为您提供属性的覆盖值。所以你最终可能会得到不正确的值。
-
你可以在任何你需要的地方使用
@Autowired protected Environment env;,它是一个单例,所以它只加载一次。 -
问题是如何写干净的属性单例?
-
你能帮帮我吗?
-
我认为您在这里忽略了这一点,
@Autowired protected Environment env;属性已经是 spring 提供的一个干净的单例。由于您已经在使用 Spring,您可以注入它。此外,您可以使用@Value注入特定值。我不知道您为什么要尝试从单例创建单例。您是否需要从静态方法调用来获取属性?如果需要,为什么?看来您在这里遇到了设计问题。
标签: spring-boot properties configuration autowired postconstruct