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;
}
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With