zoukankan      html  css  js  c++  java
  • Spring自动注入properties文件

    话不多说,直接切入正题:

    1. 因为在下面要用到Spring的<util />配置,所以,首先要引入其对应的命名空间,即要在applicationContext.xml中加入以下的配置:

    Xml代码  收藏代码
    1. xmlns:util="http://www.springframework.org/schema/util"  
    2.     xsi:schemaLocation="  
    3.      http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">  

    2.既然要让Spring使用注解来自动注入,则要让其去对自己的配置的类进行注解组件的扫描,则需要配置如下(根据自己的路径进行修改配置):

    Xml代码  收藏代码
    1. <context:component-scan base-package="com.manpedia" >  
    2. </context:component-scan>  

    3. 创建一个资源文件,具体为止视自己的项目而定,我的文件放在 resource/webconfig/sys.properties,内容如下:

    Java代码  收藏代码
    1. test=testdata  

    4. 让Spring载入资源文件,在applicationContext.xml 加入以下配置:

    Xml代码  收藏代码
    1. <!-- Web Configuration -->  
    2. <util:properties id="sys" location="classpath:webconfig/sys.properties"/>  

    5. 创建java文件,让Spring注入从资源文件中读取到的属性的值,,为了简便,我把几种注入的方式直接写入到一个文件中进行展示:

    Java代码  收藏代码
    1. /** 
    2.  * @Description: 系统相关的常量类 
    3.  * @Author: Jianguo Shang 
    4.  * @Createtime: 2014-07-11 23:20 
    5.  */  
    6. @Component  
    7. public class SysConf {  
    8.   
    9.     @Value("#{sys.test}")  
    10.     private String test;  
    11.   
    12.     @Value("#{sys.test}")  
    13.     public void setTest(String test){  
    14.         test = test;  
    15.     }  
    16.   
    17.     @Value("#{sys}")  
    18.     public void setSysConf(Properties sys){  
    19.         test= sys.getProperty("test");  
    20.     }  
    21. }  

     注意:这里的#{sys} 是与第四步的id=sys 相对应的

    另外,这里我是针对Component注解来作为例子的,但是在使用的时候,可以根据自己的需求,在Service,Controller中也是可以使用这种注解方式来注入资源文件的额值得。

    来源:http://1358440610-qq-com.iteye.com/blog/2090955

  • 相关阅读:
    vue element-ui 饿了么布局,gutter间距碰上bordr 会失效
    Linux 常用命令
    阿里云部署,ubuntu, 连接服务器 |更新源| 安装node |安装mysql
    常用 shell 命令 chmod | root
    node 进程管理 child_process [spawn,exec] | 珠峰培训node正式课 网络爬虫
    html2canvas用法的总结(转载)
    使用nvm-windows安装nodejs遇到的问题(转载)
    Can’t call setState (or forceUpdate) on an unmounted component 警告处理方法
    webpack 搭建问题汇总
    webpack执行命令参数
  • 原文地址:https://www.cnblogs.com/lidj/p/5263136.html
Copyright © 2011-2022 走看看