从非 spring 托管 bean 中获取配置值

Web*_*net 5 java spring

我正在为我的应用程序使用注释配置,而不是 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;
Run Code Online (Sandbox Code Playgroud)

在这个文件中,我注意到我可以从@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Sot*_*lis 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 
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,基本上在任何引用 the 的地方ApplicationContext,都可以获得 a@PropertySources或 a中声明的属性PropertySourcesPlaceholderConfigurer

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

@Bean
public ApplicationContextProvider contextProvider() {
    return new ApplicationContextProvider();
}
Run Code Online (Sandbox Code Playgroud)