spring中注入屬性文件中的值

方法1:
1、屬性文件配置

<!-- 獲取properties中的值 -->  
 <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
   <property name="locations">  
     <list>  
     <value>classpath:conf.properties</value>  
     </list>  
   </property>  
 </bean>  

 <!-- Spring的動態變量,能在bean中直接調用 -->   
 <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
     <property name="properties" ref="configProperties" />  
 </bean>
 <!-- 配置掃描包 -->
 <context:component-scan base-package="com.xxx.hyweb" />

2、使用
properties中SERVICE_URL=http://sxxxx.com

@Component
public class ConfUitl {
 @Value("#{configProperties['SERVICE_URL']}")
 private String url;
 public String getUrl(){
  return url;
 }
 public void setUrl(String url){
  this.url = url;
 }
}

方法2:
1、配置

<util:properties id="propertyConfigurer" location="classpath:global.properties"/>
<context:property-placeholder properties-ref="propertyConfigurer" ignore-unresolvable="true"/>

2、使用
properties中test.key = 542421ae23d4f;

@Service
public class Service{
    @Value("${test.key}")
    private String key;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章