1. 程式人生 > 程式設計 >SpringBoot注入配置檔案的3種方法詳解

SpringBoot注入配置檔案的3種方法詳解

這篇文章主要介紹了SpringBoot注入配置檔案的3種方法詳解,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

方案1:@ConfigurationProperties+@Component

定義spring的一個實體bean裝載配置檔案資訊,其它要使用配置資訊是注入該實體bean

/**
 * 將配置檔案中配置的每一個屬性的值,對映到這個元件中
 * @ConfigurationProperties:告訴SpringBoot將本類中的所有屬性和配置檔案中相關的配置進行繫結;
 *   prefix = "person":配置檔案中哪個下面的所有屬性進行一一對映
 *
 * 只有這個元件是容器中的元件,才能容器提供的@ConfigurationProperties功能;
 *
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
​
  private String lastName;
  private Integer age;
  private Boolean boss;
  private Date birth;
​
  private Map<String,Object> maps;
  private List<Object> lists;
  private Dog dog;

方案2:@Bean+@ConfigurationProperties

我們還可以把@ConfigurationProperties還可以直接定義在@bean的註解上,這是bean實體類就不用@Component和@ConfigurationProperties了,這邊是Boot的動態資料來源切換的類。

package com.topcheer.oss.base.datasource;
​
import com.alibaba.druid.pool.DruidDataSource;
​
import com.xiaoleilu.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.xiaoleilu.hutool.crypto.symmetric.SymmetricCrypto;
import com.xiaoleilu.hutool.util.CharsetUtil;
import com.xiaoleilu.hutool.util.HexUtil;
​
import lombok.extern.slf4j.Slf4j;
​
@Slf4j
public class UmspscDataSource extends DruidDataSource {
​
  private static final long serialVersionUID = 4766401181052251539L;
​
  private String passwordDis;
  
  /**
   * 密匙
   */
  private final static String Pkey ="1234565437892132";
  
  @Override
  public String getPassword() {
    if(passwordDis != null && passwordDis.length() > 0) {
      return passwordDis;
    }
    String encPassword = super.getPassword();
    if(null == encPassword) {
      return null;
    }
    log.info("資料庫密碼加解密,{" + encPassword + "}");
    try {
      // 密文解密,解密方法可以修改
      String key = HexUtil.encodeHexStr(Pkey);
      SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES,key.getBytes());
      passwordDis = aes.decryptStr(encPassword,CharsetUtil.CHARSET_UTF_8);
      return passwordDis;
    } catch (Exception e) {
      log.error("資料庫密碼解密出錯,{"+encPassword + "}");
      //log.error(LogUtil.e(e));
      //throw new Exception("資料庫密碼解密失敗!",e);
      return null;
    }
  }
}
@Bean(name = "systemDataSource")
  @ConfigurationProperties(ignoreUnknownFields = false,prefix = "spring.datasource.system")
  public DataSource systemDataSource() {
    return new UmspscDataSource();
  }
​
  @Bean(name = "secondDataSource")
  @ConfigurationProperties(ignoreUnknownFields = false,prefix = "spring.datasource.second")
  public DataSource secondDataSource() {
    return new UmspscDataSource();
  }
  
  @Bean(name="systemJdbcTemplate")
  public JdbcTemplate systemJdbcTemplate(
      @Qualifier("systemDataSource") DataSource dataSource) {
    return new JdbcTemplate(dataSource);
  }
  
  @Bean(name="secondJdbcTemplate")
  public JdbcTemplate secondJdbcTemplate(
      @Qualifier("secondDataSource") DataSource dataSource) {
    return new JdbcTemplate(dataSource);
  }

方案3:@ConfigurationProperties + @EnableConfigurationProperties

我們和上面例子一樣註解屬性,然後用 Spring的@Autowire來注入 mail configuration bean:

package com.dxz.property;
​
import org.springframework.boot.context.properties.ConfigurationProperties;
​
@ConfigurationProperties(locations = "classpath:mail.properties",ignoreUnknownFields = false,prefix = "mail")
public class MailProperties {
  private String host;
  private int port;
  private String from;
  private String username;
  private String password;
  private Smtp smtp;
​
  // ... getters and setters
  public String getHost() {
    return host;
  }
​
  public void setHost(String host) {
    this.host = host;
  }
​
  public int getPort() {
    return port;
  }
​
  public void setPort(int port) {
    this.port = port;
  }
​
  public String getFrom() {
    return from;
  }
​
  public void setFrom(String from) {
    this.from = from;
  }
​
  public String getUsername() {
    return username;
  }
​
  public void setUsername(String username) {
    this.username = username;
  }
​
  public String getPassword() {
    return password;
  }
​
  public void setPassword(String password) {
    this.password = password;
  }
​
  public Smtp getSmtp() {
    return smtp;
  }
​
  public void setSmtp(Smtp smtp) {
    this.smtp = smtp;
  }
  
  @Override
  public String toString() {
    return "MailProperties [host=" + host + ",port=" + port + ",from=" + from + ",username=" + username
        + ",password=" + password + ",smtp=" + smtp + "]";
  }
​
  public static class Smtp {
    private boolean auth;
    private boolean starttlsEnable;
​
    public boolean isAuth() {
      return auth;
    }
​
    public void setAuth(boolean auth) {
      this.auth = auth;
    }
​
    public boolean isStarttlsEnable() {
      return starttlsEnable;
    }
​
    public void setStarttlsEnable(boolean starttlsEnable) {
      this.starttlsEnable = starttlsEnable;
    }
  }
}

啟動類及測試類:

package com.dxz.property;
​
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
​
@RestController
@SpringBootApplication
@EnableConfigurationProperties(MailProperties.class)
public class TestProperty1 {
​
  @Autowired
  private MailProperties mailProperties;
  
  @RequestMapping(value = "/hello",method = RequestMethod.GET)
  @ResponseBody
  public String hello() {
    System.out.println("mailProperties" + mailProperties);
    return "hello world";
  }
​
  public static void main(String[] args) {
    //SpringApplication.run(TestProperty1.class,args);
    new SpringApplicationBuilder(TestProperty1.class).web(true).run(args);
​
  }
}

結果:

請注意@EnableConfigurationProperties註解。該註解是用來開啟對@ConfigurationProperties註解配置Bean的支援。也就是@EnableConfigurationProperties註解告訴Spring Boot 能支援@ConfigurationProperties。如果不指定會看到如下異常:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.dxz.property.MailProperties] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

注意: 還有其他辦法 (Spring Boot 總是有其他辦法!) 讓@ConfigurationProperties beans 被新增 – 用@Configuration或者 @Component註解,這樣就可以在 component scan時候被發現了。

@ConfigurationProperties @Value
功能 批量注入配置檔案中的屬性 一個個指定
鬆散繫結(鬆散語法) 支援 不支援
SpEL 不支援 支援
JSR303資料校驗 支援 不支援
複雜型別封裝 支援 不支援

配置檔案yml還是properties他們都能獲取到值;

如果說,我們只是在某個業務邏輯中需要獲取一下配置檔案中的某項值,使用@Value;

如果說,我們專門編寫了一個javaBean來和配置檔案進行對映,我們就直接使用@ConfigurationProperties;

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。