网站建设资讯

NEWS

网站建设资讯

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 maps;
  private List 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);
​
  }
}

结果:

SpringBoot注入配置文件的3种方法详解

请注意@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;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


文章标题:SpringBoot注入配置文件的3种方法详解
网站链接:http://njwzjz.com/article/pogpos.html