SpringBoot-屬性直接注入


SpringBoot-屬性直接注入

SpringBoot-屬性直接注入

上面我們說到,如果公共的屬性,我們可以使用Java類加載Properties文件,來達到復用的目的,在SpringBoot中,我們提供了更為簡單的方法,即直接使用配置文件注入。

使用直接注入我們有以下的幾個注意點:

  1. Properties文件中的key(如果有前綴則是前綴后的值 )必須和屬性名一致

  2. 在需要使用到Properties屬性文件中屬性的方法上加上@ConfigurationProperties(“prefix=xxx”)

  3. 一定要提供要注入類的getter、setter方法

packagecn.rayfoo.config;

importcom.alibaba.druid.pool.DruidDataSource;
importlombok.Data;
importlombok.ToString;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.boot.context.properties.ConfigurationProperties;
importorg.springframework.boot.context.properties.EnableConfigurationProperties;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.context.annotation.PropertySource;

importjavax.sql.DataSource;

/**
* @author 張瑞豐
* @description
* @date 2019/11/4
*/
@Configuration
publicclassJDBCConfig{

   @ConfigurationProperties(prefix="jdbc")
   publicDataSourcedataSource(JDBCPropertiesjdbcProperties){
       DruidDataSourcedruidDataSource=newDruidDataSource();
       //這里會自動setter屬性
       returndruidDataSource;
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM