如何自动装配Spring Environment对象 [英] How to autowire a Spring Environment object

查看:370
本文介绍了如何自动装配Spring Environment对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从应用程序对象中的.properties文件获取属性。我唯一的了解方法是通过 Environment 对象。

I'm attempting to get properties from a .properties file within an object of my application. My only knowledge of how to do this is via the Environment object.

在我的配置中效果很好。 。

It works great in my configuration...

@Configuration
@ComponentScan(basePackages = {
        "com.production"
})
@PropertySource(value = {
        "classpath:/application.properties",
        "classpath:/environment-${FETTER_ENVIRONMENT}.properties"
})
@EnableJpaRepositories("com.production.repositories")
@EnableTransactionManagement
public class Config {
    private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    private static final String PROPERTY_NAME_DATABASE_USER = "db.user";
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";

    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";

    @Resource
    Environment environment;

但是我尝试在另一堂课中使用,它为空。我曾尝试使用 @Resource @Autowired 以及手动注入。

But I try to do it in another class and it's null. I've tried using @Resource and @Autowired and manual injection.

环境是否有某些特殊功能可以防止这种情况发生?

Is there something special about Environment that's preventing this?

@Component
public class Vendor {
    private String token;

    @Autowired
    private Environment environment;

    public Vendor() {
        //get token from config
        //Environment environment = (Environment) ApplicationContextProvider.getApplicationContext().getBean("environment");
        setToken(environment.getProperty("api.vendor.token"));
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
}

更新:我发现此资源突出显示了<$ c $的用法c> @Value ,但我在应用程序中未使用任何XML配置。

Update: I found this resource which highlights the usage of @Value, but I don't use any XML configuration in my application.

看起来这可能就是我寻找:以编程方式加载Spring 3.1中的属性

It looks like this might be what I'm looking for: Loading properties in Spring 3.1 programmatically

推荐答案

您需要使用 @ Value 注释。但是在要求在xml中声明< context:property-placeholder 之前。

You need to use @Value annotaion for it. But before it is required to declare <context:property-placeholder in xml.

请参见此处了解详情。

另外,另一种方式:

@Inject
ApplicationContext context;
......
Enviroment env = context.getEnvironment();

这篇关于如何自动装配Spring Environment对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆