关于spring3注解@Value的使用

今天用到了将properties文件中的key注入到静态util中的问题,最终翻遍网上找到了解决方案。

1.关于spring.xml的配置

    配置文件读取,以下读取两个配置文件

  <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
    <property name="locations"> 
        <list> 
         <value>classpath*:resturl.properties</value>
         <value>classpath*:application.properties</value>
        </list> 
    </property> 
  </bean>

   <bean id="propertyConfigurer"    class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> 
      <property name="properties" ref="configProperties" /> 
  </bean> 

2.关于在java类中的使用

  由于@value不支持静态成员直接注入, 所以以下使用setter方法进行注入。同时要在类上添加@Compenent注解。

 private static  String DistributeWordURL;//分词查询URL
  @Value("${DistributeWordURL}")   
  public void setDistributeWordURL(String dwu){
      DistributeWordURL=dwu;
  }

当然,还有一项比较重要,开启类所在包的扫描,在spring中使用如下语句进行配置:

 <context:annotation-config />
 <context:component-scan base-package="com.was.*" /> 

猜你喜欢

转载自girl-luo.iteye.com/blog/2327352