【问题标题】:How to load springboot properties?如何加载弹簧启动属性?
【发布时间】: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


【解决方案1】:
@PropertySource("classpath:parameters.properties")
@PropertySource("classpath:iot.properties")
public class PropertiesHelper {

@Value( "${Value.you.need}" )
private String valueYouNeed;
}

parameters.properties

Value.you.need=12345

让它像这样,它应该在你的场景中工作。

【讨论】:

    【解决方案2】:

    优雅的解决方案

    如果你只是想消除声纳警报(声纳讨厌我的静态变量)

    // application.properties
    spring.profiles.active=test1010
    
    // IOC config bean container
    @Configuration
    @Data
    public class PropertiesConfig{
        @Value("${spring.profiles.active:preline}")
        private String profiles;
    }
    
    //Use
    @Autowired
    private PropertiesConfig propertiesConfig;
    
    @GetMapping("/getPropertiesConfig")
    public String getPropertiesConfig(){
        return propertiesConfig.getProfiles();
    }
    

    我觉得上面的方案是比较优雅的方式~,你有更好的解决方案吗?

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 2015-12-15
      • 2015-11-12
      • 1970-01-01
      • 2023-03-28
      • 2021-01-07
      相关资源
      最近更新 更多