方案1:@ConfigurationProperties+@Component
1 定义spring的一个实体bean装载配置文件信息,其它要使用配置信息是注入该实体bean 2 3 /** 4 * 将配置文件中配置的每一个属性的值,映射到这个组件中 5 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定; 6 * prefix = "person":配置文件中哪个下面的所有属性进行一一映射 7 * 8 * 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能; 9 * 10 */ 11 @Component 12 @ConfigurationProperties(prefix = "person") 13 public class Person { 14 15 private String lastName; 16 private Integer age; 17 private Boolean boss; 18 private Date birth; 19 20 private Map<String,Object> maps; 21 private List<Object> lists; 22 private Dog dog;
方案2:@Bean+@ConfigurationProperties
我们还可以把@ConfigurationProperties还可以直接定义在@bean的注解上,这是bean实体类就不用@Component和@ConfigurationProperties了,这边是Boot的动态数据源切换的类。
1 package com.topcheer.oss.base.datasource; 2 3 import com.alibaba.druid.pool.DruidDataSource; 4 5 import com.xiaoleilu.hutool.crypto.symmetric.SymmetricAlgorithm; 6 import com.xiaoleilu.hutool.crypto.symmetric.SymmetricCrypto; 7 import com.xiaoleilu.hutool.util.CharsetUtil; 8 import com.xiaoleilu.hutool.util.HexUtil; 9 10 import lombok.extern.slf4j.Slf4j; 11 12 @Slf4j 13 public class UmspscDataSource extends DruidDataSource { 14 15 private static final long serialVersionUID = 4766401181052251539L; 16 17 private String passwordDis; 18 19 /** 20 * 密匙 21 */ 22 private final static String Pkey ="1234565437892132"; 23 24 @Override 25 public String getPassword() { 26 if(passwordDis != null && passwordDis.length() > 0) { 27 return passwordDis; 28 } 29 String encPassword = super.getPassword(); 30 if(null == encPassword) { 31 return null; 32 } 33 log.info("数据库密码加解密,{" + encPassword + "}"); 34 try { 35 // 密文解密,解密方法可以修改 36 String key = HexUtil.encodeHexStr(Pkey); 37 SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key.getBytes()); 38 passwordDis = aes.decryptStr(encPassword, CharsetUtil.CHARSET_UTF_8); 39 return passwordDis; 40 } catch (Exception e) { 41 log.error("数据库密码解密出错,{"+encPassword + "}"); 42 //log.error(LogUtil.e(e)); 43 //throw new Exception("数据库密码解密失败!", e); 44 return null; 45 } 46 } 47 48 }
1 @Bean(name = "systemDataSource") 2 @ConfigurationProperties(ignoreUnknownFields = false, prefix = "spring.datasource.system") 3 public DataSource systemDataSource() { 4 return new UmspscDataSource(); 5 } 6 7 @Bean(name = "secondDataSource") 8 @ConfigurationProperties(ignoreUnknownFields = false, prefix = "spring.datasource.second") 9 public DataSource secondDataSource() { 10 return new UmspscDataSource(); 11 } 12 13 @Bean(name="systemJdbcTemplate") 14 public JdbcTemplate systemJdbcTemplate( 15 @Qualifier("systemDataSource") DataSource dataSource) { 16 return new JdbcTemplate(dataSource); 17 } 18 19 @Bean(name="secondJdbcTemplate") 20 public JdbcTemplate secondJdbcTemplate( 21 @Qualifier("secondDataSource") DataSource dataSource) { 22 return new JdbcTemplate(dataSource); 23 }
方案3:@ConfigurationProperties + @EnableConfigurationProperties
我们和上面例子一样注解属性,然后用 Spring的@Autowire
来注入 mail configuration bean:
1 package com.dxz.property; 2 3 import org.springframework.boot.context.properties.ConfigurationProperties; 4 5 @ConfigurationProperties(locations = "classpath:mail.properties", ignoreUnknownFields = false, prefix = "mail") 6 public class MailProperties { 7 private String host; 8 private int port; 9 private String from; 10 private String username; 11 private String password; 12 private Smtp smtp; 13 14 // ... getters and setters 15 public String getHost() { 16 return host; 17 } 18 19 public void setHost(String host) { 20 this.host = host; 21 } 22 23 public int getPort() { 24 return port; 25 } 26 27 public void setPort(int port) { 28 this.port = port; 29 } 30 31 public String getFrom() { 32 return from; 33 } 34 35 public void setFrom(String from) { 36 this.from = from; 37 } 38 39 public String getUsername() { 40 return username; 41 } 42 43 public void setUsername(String username) { 44 this.username = username; 45 } 46 47 public String getPassword() { 48 return password; 49 } 50 51 public void setPassword(String password) { 52 this.password = password; 53 } 54 55 public Smtp getSmtp() { 56 return smtp; 57 } 58 59 public void setSmtp(Smtp smtp) { 60 this.smtp = smtp; 61 } 62 63 @Override 64 public String toString() { 65 return "MailProperties [host=" + host + ", port=" + port + ", from=" + from + ", username=" + username 66 + ", password=" + password + ", smtp=" + smtp + "]"; 67 } 68 69 public static class Smtp { 70 private boolean auth; 71 private boolean starttlsEnable; 72 73 public boolean isAuth() { 74 return auth; 75 } 76 77 public void setAuth(boolean auth) { 78 this.auth = auth; 79 } 80 81 public boolean isStarttlsEnable() { 82 return starttlsEnable; 83 } 84 85 public void setStarttlsEnable(boolean starttlsEnable) { 86 this.starttlsEnable = starttlsEnable; 87 } 88 89 } 90 }
启动类及测试类:
1 package com.dxz.property; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.boot.autoconfigure.SpringBootApplication; 5 import org.springframework.boot.builder.SpringApplicationBuilder; 6 import org.springframework.boot.context.properties.EnableConfigurationProperties; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.bind.annotation.RequestMethod; 9 import org.springframework.web.bind.annotation.ResponseBody; 10 import org.springframework.web.bind.annotation.RestController; 11 12 @RestController 13 @SpringBootApplication 14 @EnableConfigurationProperties(MailProperties.class) 15 public class TestProperty1 { 16 17 @Autowired 18 private MailProperties mailProperties; 19 20 @RequestMapping(value = "/hello", method = RequestMethod.GET) 21 @ResponseBody 22 public String hello() { 23 System.out.println("mailProperties" + mailProperties); 24 return "hello world"; 25 } 26 27 public static void main(String[] args) { 28 //SpringApplication.run(TestProperty1.class, args); 29 new SpringApplicationBuilder(TestProperty1.class).web(true).run(args); 30 31 } 32 }
结果:
请注意@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;