Spring 属性(属性占位符)自动装配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2882545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:04:36  来源:igfitidea点击:

Spring properties (property-placeholder) autowiring

springpropertiesdependency-injection

提问by Piotr Gwiazda

I have in my applicationContext.xml

我在我的 applicationContext.xml

<context:property-placeholder location="classpath*:*.properties" />


<bean id="clientPreferencesManager" class="pl.bildpresse.bildchat2.business.ClientPreferencesManager" >
    <property name="clientApiUrl" value="${clientapi.url}" />     
</bean>

Is it possible to do the same by autowire ? Something like :

是否可以通过 autowire 做同样的事情?就像是 :

@Autowired
@Qualifier("${clientapi.url}")
public void setClientApiUrl(String clientApiUrl) {
    this.clientApiUrl = clientApiUrl;
}

回答by axtavt

You can use @Value:

您可以使用@Value

@Value("${clientapi.url}") 
public void setClientApiUrl(String clientApiUrl) { 
    this.clientApiUrl = clientApiUrl; 
}

回答by Felix

It took me some time to understand why it didn't work. I always used a #instead of a $. I always got the message:

我花了一些时间才明白为什么它不起作用。我总是使用 a#而不是 a $。我总是收到消息:

EL1008E:(pos 0): Field or property 'secretkey' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'

Just had to change it from:

只需要从:

@Value("#{secretkey}')

to

@Value('${secretkey}')

I hope this saves somebody's time.

我希望这可以节省某人的时间。

回答by Costa

Ok. Just got it. You need to add @Autowired Something like:

好的。刚拿到。您需要添加 @Autowired 类似的东西:

@Autowired
@Value("${clientapi.url}") 
private StringValueResolver resolver;

I'm using spring 3.0.0.RELEASE

我正在使用 spring 3.0.0.RELEASE

Cheers

干杯

回答by Bozho

For spring 3.0, the correct way is the one shown - using @Value("${expression}")

对于 spring 3.0,正确的方法是显示的方法 - 使用 @Value("${expression}")

For spring pre-3.0, you can try:

对于 spring pre-3.0,您可以尝试:

@Autowired
private StringValueResolver resolver;

There were no context initialization problems here, but I'm not sure it will work. Using the resolver you can resolve properties.

这里没有上下文初始化问题,但我不确定它会起作用。使用解析器,您可以解析属性。

回答by Piotr Gwiazda

My solution is to use

我的解决方案是使用

<context:property-override location="classpath:clientapi.properties" />

and then in clientapi.propertiesfile

然后在clientapi.properties文件中

clientPreferencesManager.clientApiUrl=http://localhost:8084/ClientAPI/resources/

This one is good too

这个也不错