用@Value註解直接注入properties中的值

有兩種方式可以實現@Value註解直接將properties中的值注入變量,一種是@Value("${key}"),一種是@Value("#{beanName[key]}"),他們本質上是實現了不同的類

@Value("${key}"),實現PropertyPlaceholderConfigurer

demo:https://blog.csdn.net/lyz_112233/article/details/83105165

https://blog.csdn.net/lyz_112233/article/details/83105165

https://blog.csdn.net/qing_mei_xiu/article/details/53537409

1配置properties配置文件(在applicationContext中):

  • 使用<context:property-placeholder >標籤,要配置多個properties文件則使用多個標籤
<context:property-placeholder location="classpath:xxx.properties"
    ignore-unresolvable="true" />
  • 使用PropertyPlaceholderConfigurer配置,這樣可以在list中配置多個properties文件
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

   <property name="locations">

      <list>

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

      </list>

   </property>

</bean>

 

2、Client類中Annotation的使用:

  • 註釋變量,對變量值進行注入:
@Value("${server.ip}")
private String ip;
  • 註釋方法,對輸入值進行注入(set方法不能是static的):
@Value("${getToken}")

private void setTokenUrl(String tokenUrl) {

this.tokenUrl = tokenUrl;

}

 

二、@Value("#{beanName[key]}"),實現PropertiesFactoryBean

demo:https://blog.csdn.net/w605283073/article/details/49203141

1配置properties配置文件:可以將配置整體賦給Properties類型的類變量,也可以取出其中的一項賦值給String類型的類變量

  • <util:properties/> 標籤

<util:properties/> 標籤只能加載一個文件,當多個屬性文件需要被加載的時候,可以使用多個該標籤

  • 使用PropertiesFactoryBean配置

<!-- <util:properties/> 標籤的實現類是PropertiesFactoryBean,  

 直接使用該類的bean配置,設置其locations屬性可以達到一個和上面一樣加載多個配置文件的目的 -->  

 <bean id="settings"   

   class="org.springframework.beans.factory.config.PropertiesFactoryBean">  

   <property name="locations">  

  <list>  

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

    <value>file:/opt/rms/config/rms-env.properties</value>  

  </list>  

   </property>  

 </bean>  

</beans> 

 

2Client類中Annotation的使用,有三種方式:

  • 使用@Value("#{remoteSettings['remote.ip']}")  來註釋一個string類型對象
  • 使用@Value("#{remoteSettings}")  來註釋一個Properties對象
  • 使用第二種配置方式還可以使用@Autowired對Properties對象進行注入

 

  • 如果class的靜態變量值(static)是獲取不到值的

*注意,不管是哪種注入方式,變量都不能被static和final修飾,否則會出現變量獲取不到值的情況

如果變量必須是static的,那麼可以通過非static的setter方法來進行注入,此時@Value必須修飾在方法上,且set方法不能有static :

private static String CLUSTER_NAME;

@Value("${ES.CLUSTER_NAME}")

public void setClusterName(String clusterName) {

CLUSTER_NAME = clusterName;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章