通过@Value注解获取*.properties文件中的配置

示例:

 1 package com.disappearwind;
 2 
 3 import org.springframework.beans.factory.annotation.Value;
 4 import org.springframework.stereotype.Component;
 5 
 6 @Component
 7 public class Config {
 8     
 9     /***
10      * 是否允许缓存
11      */
12     @Value("${cache.enable}")
13     String enable;
14     public Boolean getEnable(){
15         return enable != null && enable.equals("true");
16     }
17 }
Config.java

 

1 cache.enable=true
config.properties

 

配置和使用上需要注意的点:

1.context.xml

<context:component-scan base-package="com.disappearwind.*" />
<context:property-placeholder location="classpath:conf/config.properties" />

如果是Controller层还需要在servlet.xml中加入
<context:component-scan base-package="com.disappearwind.controller" />

2. 使用的类必须标识
@Component 或 @Service 等Spring托管

3. 注解使用时机

不能在构造函数中,如果确实需要在初始化的时候调用,那在需要执行的方法上加@PostConstruct注解

类的构造交由Spring装配,不要自己new

posted @ 2015-07-01 11:33  消失的风  阅读(406)  评论(0)    收藏  举报