在controller中無法通過註解@Value獲取到配置文件中定義的值解決辦法
阿新 • • 發佈:2019-04-10
component value wired pat lac ice rop 獲取 mvc 使用springMVC的朋友,有時候可能會遇到以下問題:
想在controller中使用@Value指定變量,但是無法得到對應的值。而在server層獲取,是正常的。
解決方案:
1:在srping-mvc.xml 加上以下配置。相當於在springmvc配置文件中也讀取properties文件,這樣controller就訪問自己容器中的數據
<context:property-placeholder location="classpath:config.properties" ignore-unresolvable="true" />
2:在父容器中註冊一個公用Bean,然後把配置文件的值註入到這個Bean中
因為Service層的對象是有Spring容器創建,因此我們定義一個Component: AccOauthUtils,註入進來屬性用public修飾
@Component
public class AccOauthUtils {
@Value("${accStatus}")
public String accStatus;
在controller註入(必須通過@Autowired註解,通過new AccOauthUtils的形式無法獲取值):
@Autowired
private AccOauthUtils accOauthUtils;
再通過 accOauthUtils.accStatus獲取
在controller中無法通過註解@Value獲取到配置文件中定義的值解決辦法