美文网首页
02_Springmvc的Controller提取常量到配置文件

02_Springmvc的Controller提取常量到配置文件

作者: 明天你好向前奔跑 | 来源:发表于2017-09-01 18:29 被阅读0次

    今天在做练习的时候,有几个变量在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中就可以成功。

    相关文章

      网友评论

          本文标题:02_Springmvc的Controller提取常量到配置文件

          本文链接:https://www.haomeiwen.com/subject/grpkjxtx.html