相关疑难解决方法(0)

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

我正在为我的应用程序使用注释配置,而不是 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)

java spring

5
推荐指数
1
解决办法
4803
查看次数

标签 统计

java ×1

spring ×1