這篇文章主要介紹了SpringBoot注入配置文件的3種方法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
在萬秀等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供成都網(wǎng)站制作、網(wǎng)站設(shè)計(jì) 網(wǎng)站設(shè)計(jì)制作按需規(guī)劃網(wǎng)站,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站設(shè)計(jì),營銷型網(wǎng)站建設(shè),成都外貿(mào)網(wǎng)站建設(shè)公司,萬秀網(wǎng)站建設(shè)費(fèi)用合理。
方案1:@ConfigurationProperties+@Component
定義spring的一個(gè)實(shí)體bean裝載配置文件信息,其它要使用配置信息是注入該實(shí)體bean /** * 將配置文件中配置的每一個(gè)屬性的值,映射到這個(gè)組件中 * @ConfigurationProperties:告訴SpringBoot將本類中的所有屬性和配置文件中相關(guān)的配置進(jìn)行綁定; * prefix = "person":配置文件中哪個(gè)下面的所有屬性進(jìn)行一一映射 * * 只有這個(gè)組件是容器中的組件,才能容器提供的@ConfigurationProperties功能; * */ @Component @ConfigurationProperties(prefix = "person") public class Person { private String lastName; private Integer age; private Boolean boss; private Date birth; private Mapmaps; private List
方案2:@Bean+@ConfigurationProperties
我們還可以把@ConfigurationProperties還可以直接定義在@bean的注解上,這是bean實(shí)體類就不用@Component和@ConfigurationProperties了,這邊是Boot的動(dòng)態(tài)數(shù)據(jù)源切換的類。
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("數(shù)據(jù)庫密碼加解密,{" + 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("數(shù)據(jù)庫密碼解密出錯(cuò),{"+encPassword + "}"); //log.error(LogUtil.e(e)); //throw new Exception("數(shù)據(jù)庫密碼解密失??!", 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; } } }
啟動(dòng)類及測(cè)試類:
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); } }
結(jié)果:
請(qǐng)注意@EnableConfigurationProperties注解。該注解是用來開啟對(duì)@ConfigurationProperties注解配置Bean的支持。也就是@EnableConfigurationProperties注解告訴Spring Boot 能支持@ConfigurationProperties。如果不指定會(huì)看到如下異常:
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時(shí)候被發(fā)現(xiàn)了。
@ConfigurationProperties | @Value | |
---|---|---|
功能 | 批量注入配置文件中的屬性 | 一個(gè)個(gè)指定 |
松散綁定(松散語法) | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303數(shù)據(jù)校驗(yàn) | 支持 | 不支持 |
復(fù)雜類型封裝 | 支持 | 不支持 |
配置文件yml還是properties他們都能獲取到值;
如果說,我們只是在某個(gè)業(yè)務(wù)邏輯中需要獲取一下配置文件中的某項(xiàng)值,使用@Value;
如果說,我們專門編寫了一個(gè)javaBean來和配置文件進(jìn)行映射,我們就直接使用@ConfigurationProperties;
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。