Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining config values from within non-spring managed bean

Tags:

java

spring

I'm using annotation-configuration, not XML for my application...

@Configuration
@ComponentScan(basePackages = {
        "com.production"
    })
@PropertySource(value= {
        "classpath:/application.properties",
        "classpath:/environment-${COMPANY_ENVIRONMENT}.properties"
})
@EnableJpaRepositories("com.production.repository")
@EnableTransactionManagement
@EnableScheduling
public class Config {
    @Value("${db.url}")
    String PROPERTY_DATABASE_URL;
    @Value("${db.user}")
    String PROPERTY_DATABASE_USER;
    @Value("${db.password}")
    String PROPERTY_DATABASE_PASSWORD;

    @Value("${persistenceUnit.default}")
    String PROPERTY_DEFAULT_PERSISTENCE_UNIT;

In this file I've noticed I can obtain configuration values from the @PropertySource files. How can I obtain these values outside of a spring managed bean?

Is it possible for me to use my ApplicationContextProvider to obtain these values?

public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext (ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}
like image 392
Webnet Avatar asked Oct 02 '22 20:10

Webnet


1 Answers

If I understand you correctly, yes you can use your ApplicationContextProvider class. @PropertySource properties end up in the ApplicationContext Environment. You can therefore access them like

public static class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext (ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        Environment env = applicationContext.getEnvironment();
        System.out.println(env.getProperty("db.user")); // access them 
    }
}

So basically anywhere you have a reference to the ApplicationContext, you can get the properties declared in a @PropertySources or a PropertySourcesPlaceholderConfigurer.

However, in this case, the ApplicationContextProvider will have to be declared as a Spring bean in your context.

@Bean
public ApplicationContextProvider contextProvider() {
    return new ApplicationContextProvider();
}
like image 130
Sotirios Delimanolis Avatar answered Oct 13 '22 11:10

Sotirios Delimanolis