Controller層使用@value註解獲取不到properties屬性值
阿新 • • 發佈:2018-12-14
說到@Value註解,用過的應該都知道,這是Spring3的一個註解,通過@value註解的方式獲取properties檔案中的配置值,大大簡化了我們讀取配置檔案的程式碼。然而,最近在使用中發現在controller使用出現了獲取不到值的問題
經過排查發現父子容器的說法,
父子容器:
Spring容器 -- 父容器
SpringMVC容器 -- 子容器
父子容器的關係:子容器能夠訪問父容器的資源(bean), 如:Controller可以注入Service,但是:父容器不能訪問子容器的資源
子容器可以訪問父容器的物件,但是@Value並不會主動去父容器中查詢配置檔案屬性值。properties檔案是在applicationContext.xml讀取的,這是現在的問題。
解決問題:
1.在springmvc配置檔案中也讀取properties檔案,這樣controller就訪問自己容器中的資料
2.在父容器中註冊一個Bean,然後把配置檔案的值注入到這個Bean中,然後子容器可以訪問到這個bean,自然可以訪問到屬性,
因為Service層的物件是有Spring容器建立,因此我們定義一個Service: PropertiesService,注入進來屬性用public修飾
@Service public class PropertyService { @Value("${PAGENUM}") public int PAGENUM; }
在controller注入:
@Autowired private PropertyService propertyService;
再通過 propertyService.PAGENUM獲取