---
title: "Spring自动注入properties文件"
author: "liyonghui160com"
date: "2016-10-13T15:29:02Z"
tags: ["Java", "Spring"]
categories: ["互联网"]
slug: "spring-properties"
draft: false
lastmod: "2016-10-13T15:29:02Z"
id: 2330360
url: "https://liyonghui160com.iteye.com/blog/2330360"
---

1\. 因为在下面要用到Spring的&lt;util /&gt;配置，所以，首先要引入其对应的命名空间，即要在applicationContext.xml中加入以下的配置：

Xml代码  [![收藏代码](http://1358440610-qq-com.iteye.com/images/icon_star.png)]()

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"&gt;

 

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

Xml代码  [![收藏代码](http://1358440610-qq-com.iteye.com/images/icon_star.png)]()

1. &lt;context:component-scan base-package="com.manpedia" &gt;
2. &lt;/context:component-scan&gt;

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

Java代码  [![收藏代码](http://1358440610-qq-com.iteye.com/images/icon_star.png)]()

1. test=testdata

 

4\. 让Spring载入资源文件，在applicationContext.xml 加入以下配置：

Xml代码  [![收藏代码](http://1358440610-qq-com.iteye.com/images/icon_star.png)]()

1. &lt;!-- Web Configuration --&gt;
2. &lt;util:properties id="sys" location="classpath:webconfig/sys.properties"/&gt;

 

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

Java代码  [![收藏代码](http://1358440610-qq-com.iteye.com/images/icon_star.png)]()

01. /\**
02. * @Description: 系统相关的常量类
03. * @Author: Jianguo Shang
04. * @Createtime: 2014-07-11 23:20
05. \*/
06. @Component
07. public class SysConf {
08. @Value("${sys.test}")
09. private String test;
10. @Value("${sys.test}")
11. public void setTest(String test){
12. test = test;
13. }
14. @Value("${sys}")
15. public void setSysConf(Properties sys){
16. test= sys.getProperty("test");
17. }
18. }

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