目标
在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文件位置。