Ihor M.
Ihor M.

Reputation: 3148

Obtaining instance of ConfigurationProperties without using @Autowire

Is there a way to obtain a bean annotated with @ConfigurationProperties annotation by not using the @Autowire annotation, but by rather providing a prefix?

I have this constraint annotation, where I am passing the name of the property that helps with decision making with regards to validation. By knowing the fully qualified name of the property, I would like to check out the value of that key

Upvotes: 0

Views: 383

Answers (2)

Ihor M.
Ihor M.

Reputation: 3148

In order to override a property and then to roll it back:

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");
    }
}

Upvotes: 0

Andreas
Andreas

Reputation: 159260

By knowing the fully qualified name of the property, I would like to check out the value of that key

Then go get the property:

@Autowired
private Environment env;

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

Upvotes: 2

Related Questions