@Controller 类中的 Spring @Value 注释不评估属性文件中的值 [英] Spring @Value annotation in @Controller class not evaluating to value inside properties file
问题描述
我是 Spring 的新手,并尝试使用 @Value("${loginpage.message}")
注释注入一个带有值的字符串,该注释位于用 @ 注释的控制器内Controller
注释和我的字符串的值被评估为字符串 "${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" />
我的属性文件有一行:
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.
推荐答案
问题好像已经有人问过了Spring 3.0.5 不从属性评估@Value 注释
It seems that the question has been already asked Spring 3.0.5 doesn't evaluate @Value annotation from properties
Web 应用程序根和 servlet 应用程序上下文之间的差异是 Spring 中最容易混淆的来源之一,请参阅 Spring框架中applicationContext.xml和spring-servlet.xml的区别
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屋!