Spring3中用注解直接注入properties中的值

来源:互联网 发布:仿京东商城源码 php 编辑:程序博客网 时间:2024/06/05 19:30

在bean(可以是controller, service, dao等)中,使用@Value注解:

 

@Service

publicclass TmsRemoteService {

  

   @Value("${tmsremoteservice.url}"

   privateString url;

}

 

在spring配置文件里:


<!-- 将多个配置文件读取到容器中,交给Spring管理 --> 

    <beanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 

        <propertyname="locations"> 

           <list> 

              <!--这里支持多种寻址方式:classpathfile--> 

              <value>classpath:config.properties</value>

              <!--推荐使用file的方式引入,这样可以将配置和代码分离 --> 

              <!--<value>file:/opt/demo/config/demo-mq.properties</value> --> 

            

            </list> 

        </property> 

</bean> 

 

config.properties文件:

tmsremoteservice.url =fdsafddsafsdadfd



这样config.properties中的tmsremoteservice.url就注入到url属性中了

 

PS:如果是在spring配置文件里注入需在方法中提供setter方法

<beanid="tmsRemoteService"

       class="com.bsis2.work.logic.TmsRemoteService">

        <property name="url">

          <value>${tmsremoteservice.url}</value>

      </property>

 </bean>

0 0