在不使用@Autowire的情况下获取ConfigurationProperties的实例

时间:2019-06-10 18:49:29

标签: java spring spring-boot

是否有一种方法可以通过不使用@ConfigurationProperties注释,而是通过提供@Autowire来获得带有prefix注释的bean?

我有这个约束注释,我在其中传递了有助于进行验证决策的属性名称。通过知道属性的全限定名,我想检查该键的值

2 个答案:

答案 0 :(得分:2)

  

通过知道属性的全限定名,我想检查该键的值

然后去获取属性:

@Autowired
private Environment env;

// method here
    String value = this.env.getProperty(propName);

答案 1 :(得分:0)

为了覆盖属性然后将其回滚:

protected void overrideProperties(Map<String, String> overrideMap) {
    log.info("Overriding properties = {}", overrideMap);
    Environment env = appContext.getEnvironment();
    if (env instanceof ConfigurableEnvironment) {
        ConfigurableEnvironment confEnv = (ConfigurableEnvironment) env;
        MutablePropertySources sources = confEnv.getPropertySources();
        // removing in case rollback was not done
        if (sources.contains(TEST_RESOURCE_PROPERTIES_OVERRIDE_NAME)) {
            sources.remove(TEST_RESOURCE_PROPERTIES_OVERRIDE_NAME);
        }
        Properties overrides = new Properties();
        overrides.putAll(overrideMap);
        sources.addFirst(new PropertiesPropertySource(TEST_RESOURCE_PROPERTIES_OVERRIDE_NAME, overrides));
        // this triggers changes in beans annotated with @ConfigurationProperties and updates @Value fields
        appContext.publishEvent(new EnvironmentChangeEvent(overrideMap.keySet()));
    }
    // this should never happen
    else {
        log.info("Unable to override properties as Environment is not of type ConfigurableEnvironment");
    }
}

protected void rollbackOverriddenProperties(Map<String, String> overrideMap) {
    log.info("Rolling back properties = {}", overrideMap);
    Environment env = appContext.getEnvironment();
    if (env instanceof ConfigurableEnvironment) {
        ConfigurableEnvironment confEnv = (ConfigurableEnvironment) env;
        MutablePropertySources sources = confEnv.getPropertySources();
        sources.remove(TEST_RESOURCE_PROPERTIES_OVERRIDE_NAME);
        // this triggers changes in beans annotated with @ConfigurationProperties and updates @Value fields
        appContext.publishEvent(new EnvironmentChangeEvent(overrideMap.keySet()));
    }
    // this should never happen
    else {
        log.info("Unable to rollback overridden properties as Environment is not of type ConfigurableEnvironment");
    }
}