我在我的应用程序中使用注释配置,而不是 XML...
@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;
在这个文件中,我注意到我可以从以下位置获取配置值@PropertySource
文件。如何在 Spring 托管 bean 之外获取这些值?
我可以使用我的ApplicationContextProvider
来获取这些值?
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public void setApplicationContext (ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
}
如果我理解正确的话,是的,你可以使用你的ApplicationContextProvider
class. @PropertySource
属性最终在ApplicationContext
Environment
。因此,您可以像这样访问它们
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
}
}
所以基本上任何你可以参考的地方ApplicationContext
,您可以获得在 a 中声明的属性@PropertySources
or a PropertySourcesPlaceholderConfigurer
.
然而,在这种情况下,ApplicationContextProvider
必须在您的上下文中将其声明为 Spring bean。
@Bean
public ApplicationContextProvider contextProvider() {
return new ApplicationContextProvider();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)