---
title: "spring注解获取properties文件中的值"
author: "静默时间-花开灿然"
date: "2015-08-08T19:42:29Z"
tags: []
categories: ["研发管理"]
slug: "spring-properties"
draft: false
lastmod: "2015-08-08T19:42:29Z"
id: 2233788
url: "https://zhen217.iteye.com/blog/2233788"
---

properties文件格式如下：(xxx\_common.properties)

```
xxx.base.path=http://localhost:8080/xxx/
```

 spring文件中使用注解扫描且加载属性文件：

```
<context:component-scan base-package="com.xxx.xxx" />
<util:properties id="common" location="classpath:xxx_common.properties" />
```

要使用util:properties加上约束 即可：

```
xmlns:util="http://www.springframework.org/schema/util"

xsi:schemaLocation="http://www.springframework.org/schema/util 
http://www.springframework.org/schema/util/spring-util.xsd"
```

 

使用注解的类：(com.xxx.xxx)

```
@Repository("com.xxx.xxx.vo.CommonProperties")
public class CommonProperties {
@Value("#{common['xxx.base.path']}")
public String basePath;
public String getBasePath() {
  return basePath;
 }.......
```

 注意：这里@Value("#{common\['xxx.base.path']}")的common和这个&lt;util:properties id="common"的id一致。\['xxx.base.path']即是属性文件的key。  
接下来，我们就可以调用该类CommonProperties 的get方法获取路径值了。

如可以在Controller类里使用：

```
@Autowired
protected CommonProperties commonProperties;
........
System.out.println(this.commonProperties.getBasePath());

```