java 如何将属性值注入到注释配置的 spring mvc 3.0 控制器中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2055660/
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-10-29 19:09:47  来源:igfitidea点击:

How can I inject a property value into an annotation configured spring mvc 3.0 controller

javaspring

提问by l3dx

First: I'm using Spring 3.0

第一:我使用的是 Spring 3.0

I have a problem when configuring my controller class. The controller uses a web service which I want to define the endpoint address using a .properties file.

配置控制器类时遇到问题。控制器使用我想使用 .properties 文件定义端点地址的 Web 服务。

@Controller
public class SupportController {

    @Value("#{url.webservice}") 
    private String wsEndpoint;

    ...

In my application context xml-file, I've defined this:

在我的应用程序上下文 xml 文件中,我定义了这个:

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

I've been reading the documentation, trying different approaches (like adding prefix systemProperties.),but I keep getting an error message telling me that it doesn't exist.

我一直在阅读文档,尝试不同的方法(例如添加前缀systemProperties.),但我不断收到一条错误消息,告诉我它不存在。

Field or property 'url' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'

在“org.springframework.beans.factory.config.BeanExpressionContext”类型的对象上找不到字段或属性“url”



Ok. I've figured it out.

行。我已经想通了。

Now, in the controller:

现在,在控制器中:

@Value("#{settings['url.webservice']")

Then in the context configuration I have this "helper bean":

然后在上下文配置中,我有这个“helper bean”:

<util:properties id="settings" 
location="/WEB-INF/supportweb.properties"></util:properties>

回答by GreyFairer

This should work, too:

这也应该有效:

@Value("${url.webservice}") 
private String wsEndpoint;

回答by Enrico

I have this configuration and it works fine:

我有这个配置,它工作正常:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
       <list>
         <value>classpath:application.properties</value>
      </list>
    </property>
</bean>

and I iniejct the property in this way

我以这种方式初始化财产

@Value("${root.log.level}") 
private String prop;

the field is correctly initialized to "DEBUG" value.

该字段已正确初始化为“DEBUG”值。

回答by ykhrustalev

you should check that the

你应该检查一下

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

is defined in webmvc-config.xml where you create instances of the @Controllers

在 webmvc-config.xml 中定义,您可以在其中创建 @Controllers 的实例