@Controller类中的Spring @Value注释不评估属性文件中的值 [英] Spring @Value annotation in @Controller class not evaluating to value inside properties file
问题描述
我是Spring的新手,并尝试在使用@Controller
批注的控制器内部使用@Value("${loginpage.message}")
批注注入具有值的字符串,并且我的字符串的值被评估为字符串"${loginpage.message}"
,并且不是我的属性文件中的内容.
I am new to Spring and trying to inject a string with a value using the @Value("${loginpage.message}")
annotation inside of a controller annotated with the @Controller
annotation and the value of my string is being evaluated as the string "${loginpage.message}"
and not what is inside my properties file.
下面是我的控制器,带有要插入的字符串"message".
Below is my controller with the string 'message' that I want to inject.
@Controller
public class LoginController extends BaseController {
@Value("${loginpage.message}")
private String message;
@RequestMapping("/")
public String goToLoginPage(Model model) {
model.addAttribute("message", message);
return "/login";
}
}
我的应用程序上下文如下:
My application context looks like this:
<context:property-placeholder location="classpath:properties/application.properties" />
<context:annotation-config />
<context:component-scan base-package="com.me.application" />
我的属性文件中包含以下行:
My properties file has the line:
loginpage.message=this is a test message
Spring必须在某个时候获取该值,因为每当我将@Value("${loginpage.message}")
更改为属性文件(例如@Value("${notInPropertiesFile}")
之外)中的值时,都会出现异常.
Spring must be picking up the value at some point because whenever I change @Value("${loginpage.message}")
to a value not in the properties file like @Value("${notInPropertiesFile}")
, I get an exception.
推荐答案
It seems that the question has been already asked Spring 3.0.5 doesn't evaluate @Value annotation from properties
Web应用程序根目录和servlet应用程序上下文之间的差异是Spring混乱的主要原因之一,请参阅
The difference between web app root and servlet application contexts is one of the top sources of confusion in Spring, see Difference between applicationContext.xml and spring-servlet.xml in Spring Framework
来自@Value
javadoc:
From @Value
javadoc :
请注意,@ Value批注的实际处理是由 BeanPostProcessor
Note that actual processing of the @Value annotation is performed by a BeanPostProcessor
来自 Spring文档:
BeanPostProcessor接口是按容器划分作用域的.仅在使用容器层次结构时才有意义.如果在一个容器中定义BeanPostProcessor,它将仅对该容器中的bean进行工作.在一个容器中定义的Bean不会由另一个容器中的BeanPostProcessor进行后处理,即使这两个容器是同一层次结构的一部分.
BeanPostProcessor interfaces are scoped per-container. This is only relevant if you are using container hierarchies. If you define a BeanPostProcessor in one container, it will only do its work on the beans in that container. Beans that are defined in one container are not post-processed by a BeanPostProcessor in another container, even if both containers are part of the same hierarchy.
这篇关于@Controller类中的Spring @Value注释不评估属性文件中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!