spring注解获取properties文件中的值

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和这个<util:properties id="common"的id一致。['xxx.base.path']即是属性文件的key。
接下来,我们就可以调用该类CommonProperties 的get方法获取路径值了。

如可以在Controller类里使用:

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

猜你喜欢

转载自zhen217.iteye.com/blog/2233788