您好,登錄后才能下訂單哦!
這篇文章主要介紹了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;
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。