Spring @Value 無法獲取到properties文件中的值

在非Controller層無法通過@Value獲取值

  1. 變量不能使用 static 修改

spring mvc Controller中使用@Value無法獲取屬性值

在使用spring mvc時,實際上是兩個spring容器:
  1. dispatcher-servlet.xml 是一個,我們的controller就在這裏,所以這個裏面也需要注入屬性文件 org.springframework.web.servlet.DispatcherServlet 這裏最終是使用WebApplicationContext parent =WebApplicationContextUtils.getWebApplicationContext(getServletContext()); 創建spring容器,代碼在FrameworkServlet中
  2. applicationContext.xml 是另外一個,也需要注入屬性文件 org.springframework.web.context.ContextLoaderListener 3.我們在的service中可以拿到@Value注入的值,那是因爲我們通常都會把獲取屬性文件定義在applicationContext.xml(spring.xml)中,這樣在 Controller中是取不到的,必須在dispatcher-servlet.xml 中把獲取屬性文件再定義一下

spring xml

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章