1. 程式人生 > >Spring註釋詳解(十個)@value詳解

Spring註釋詳解(十個)@value詳解

controller讀取不到的原因: http://cdn.verydemo.com/demo_c143_i7726.html

我在之前的專案中一直使用下面的格式注入: 
Java程式碼  收藏程式碼
  1. @Value("#{config['redis.host']}")  
  2. private String  redisHost;  

使用下面的方式注入總是不成功。 
Java程式碼  收藏程式碼
  1. @Value("${redis.host}")  
  2. private String  redisHost;  

最近終於發現,掃描配置檔案的語句: 
Xml程式碼  收藏程式碼
  1. <context:property-placeholder
     location="classpath*:/xxx.properties" />  

要交給springMVC的DispatcherServlet去掃描,而不是spring的監聽器ContextLoaderListener去掃描,就可以比較方便的使用“${xxx}”去注入。 



詳細配置:

Spring MVC 通過@Value註解讀取.properties配置內容,@value.properties 

第一步: 

在applicationContext.xml配置: 

1     <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 

2         <property name="locations"> 
3             <list> 
4                 <value>classpath:/config/*.properties</value> 
5             </list> 
6         </property> 
7     </bean> 
8     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> 

9         <property name="properties" ref="configProperties" /> 
10     </bean>    
第二步: 

建立配置檔案內容: 

例如:userPageSize=5 

第三步: 

在Controller中使用註解獲得配置項內容: 

1 @Value("#{configProperties['userPageSize']}") 
2 private String userPageSize; 
第四步: 

後面的程式碼就可以使用userPageSize這個私有變量了,這個字串的值就是我們配置檔案中配置的5