在 SpringMVC Controller 中獲取 @Value 註解的值

目標

在Controller中通過@Value註解獲取*.properies文件的的值


步驟

1、準備.properties文件

(1)位置:/src/main/resources/config/demo.properties

(2)內容:REPORT_TEMPLATE_PATH=/WEB-INF/pages/reports/ReportTemplate.jasper

2、修改SpringMVC配置文件application-mvc.xml:

<context:property-placeholder ignore-unresolvable="true" location="classpath:/config/demo.properties" />

3、在Controller中啓用@Value:

	@Value("${REPORT_TEMPLATE_PATH}")
	private String REPORT_TEMPLATE_PATH;

	@RequestMapping("getReportTemplatePath")
	public void demoMethod(){
		System.out.println("REPORT_TEMPLATE_PATH = " + REPORT_TEMPLATE_PATH);
	}

4、運行結果:

REPORT_TEMPLATE_PATH = /WEB-INF/pages/reports/ReportTemplate.jasper


注意事項:

1、Controller加註@Value的變量不能是靜態的(static);

2、Controller是在子容器SpringMVC中初始化的,Service和DAO是在父容器ApplicationContext中初始化的。子容器可以訪問父容器中的對象,但不能訪問父容器中的屬性(如@Value得到的變量值),因此必須在子容器單獨配置properties文件位置。


參考資料:

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