获取非Spring管理Bean中的配置值

6

我在我的应用程序中使用注释配置,而不是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;
    }
}
1个回答

4
如果我理解正确的话,是的,你可以使用你的ApplicationContextProvider类。 @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,都可以获取在@PropertySourcesPropertySourcesPlaceholderConfigurer中声明的属性。

然而,在这种情况下,ApplicationContextProvider必须在您的上下文中声明为Spring bean。

@Bean
public ApplicationContextProvider contextProvider() {
    return new ApplicationContextProvider();
}

谢谢回复。为什么它必须被定义为 Spring bean?在我的应用程序中,我一直在静态地使用它。 - Ben
@Webnet 实际上并不需要,但如果有的话,Spring 将负责调用和设置 ApplicationContext。否则,在初始化完成后,您需要自己调用它。 - Sotirios Delimanolis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接