5

我正在为我的应用程序使用注释配置,而不是 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 之外获取这些值?

我可以使用 myApplicationContextProvider来获取这些值吗?

public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext (ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}
4

1 回答 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 
    }
}

所以基本上任何你有引用的地方,你都可以得到在 a或 aApplicationContext中声明的属性。@PropertySourcesPropertySourcesPlaceholderConfigurer

但是,在这种情况下,ApplicationContextProvider必须在您的上下文中将其声明为 Spring bean。

@Bean
public ApplicationContextProvider contextProvider() {
    return new ApplicationContextProvider();
}
于 2013-09-24T22:05:39.070 回答