今天在做练习的时候,有几个变量在controller层写死了,这样是不好的,因此将它提取到外部的配置文件中,Controller直接引用即可。
代码如下:
1. 提取变量到外部配置文件
baseDict.properties :
industryType.code=001
fromType.code=002
levelType.code=006
2. 在springmvc.xml中引入外部配置文件:
<!--注入外部配置文件-->
<context:property-placeholder location="classpath:resources/basedictcode.properties"/>
3. 在Controller层使用
@Value("${industryType.code}")
private String industryTypeCode;
@Value("${fromType.code}")
private String fromTypeCode;
@Value("${levelType.code}")
private String levelTypeCode;
这样就可成功读取到配置文件中定义的值了,这里要注意的是:
由于父子容器的关系,Spring容器不能读取到springmvc容器的内容,Springmvc可以读取到Spring的内容,
因此即使在application-dao/service.xml等属于spring容器的配置文件中引入了配置文件,例如 *.properties也不能生效。
同样配置注解扫描也是一样,但是在springmvc.xml中就可以成功。
网友评论