浅析SpringBoot自动配置的原理及实现
Posted Bom~Bang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了浅析SpringBoot自动配置的原理及实现相关的知识,希望对你有一定的参考价值。
目录
2.MybatisAutoConfiguration.class
2. 将kuaidiniao打包安装到本地仓库 mvn clean install
3.开发kuaidniao-spring-boot-starter,加依赖
7.安装快递鸟starter mvn clean install
8.在Spring-Boot项目中测试,添加starter依赖,并以前缀关键字添加属性
Spring-Boot的自动配置功能是什么?
1.什么是spring-Boot?
Spring Boot实现了自动配置,降低了项目搭建的复杂度。它主要是为了解决使用Spring框架需要进行大量的配置太麻烦的问题,所以它并不是用来替代Spring的解决方案,而是和Spring框架紧密结合用于提升Spring开发者体验的工具。同时它集成了大量常用的第三方库配置(例如Jackson, JDBC, Mongo, Redis, Mail等等),Spring Boot应用中这些第三方库几乎可以零配置的开箱即用(out-of-the-box)。
2.spring-Boot的自动配置功能
还记得曾经为了引入一个框架,而在spring的xml文件里面写一大堆的配置或者以注解的形式,定义一大堆的配置类,简直不要太繁琐,稍不注意还很容易出错。终于有一天,springboot出现了,简直就是天使般的存在,自从用上springboot,腰也不疼了,头发掉的也少了。这一切都源于Springboot自动配置的特性。
Springboot遵循“约定优于配置”的原则,使用注解对一些常规的配置项做默认配置,减少或不使用xml配置,让你的项目快速运行起来。Springboot还为大量的开发常用框架封装了starter,如今引入框架只要引入一个starter,你就可以使用这个框架,只需少量的配置甚至是不需要任何配置。
Spring-Boot 自动配置核心注解
1.@SpringBootApplication
@SpringBootApplication位于xxxApplication启动类中,进入它的源码看看
//以下四个为元注解,不是重点剖析对象
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
//标记为配置类
@SpringBootConfiguration
//启动自动配置
@EnableAutoConfiguration
//扫包,以当前类(Application类启动类)所在的包为基包递归扫描
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
........
........
}
重点关注的两个注解@SpringBootConfiguration、@EnableAutoConfiguration的源码
//忽略元注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
//标识出当前类为配置类
@Configuration
//为 Spring 的模式注解添加索引,以提升应用启动性能
//@Repository @Component @Service @Controller @Configuration(模式注解)
@Indexed
public @interface SpringBootConfiguration {
.......
.......
}
//忽略元注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
//自动配置所有的包
@AutoConfigurationPackage
//引入自动筛选注解类去筛选需要配置的bean
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
......
......
}
小结:
- Application是一个配置类,支持直接@Bean配置bean
- 默认启动了自动配置AutoConfiguration
- 包扫描,以当前类(Application类启动类)所在的包为基包递归扫描,要求所有的包与Application同级
Starter依赖的原理-以Mybits为例
找到mybits的spring.factories文件以及自动配置类
1.spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\
org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfiguration,\\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
2.MybatisAutoConfiguration.class
// *标记是一个配置类
@Configuration
//条件开关,类路径上存在SqlSessionFactory、SqlSessionFactoryBean
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
//要求有一个DataSource的Bean
@ConditionalOnSingleCandidate(DataSource.class)
//*启动配置属性,关联了一个配置属性类
@EnableConfigurationProperties(MybatisProperties.class)
//指定在某些自动配置类之后执行自动配置
@AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class })
public class MybatisAutoConfiguration implements InitializingBean {
//配置属性类,用于配置核心启动类所需参数
private final MybatisProperties properties;
...
@Bean // *该方法为你创建一个SQLSessionFactory,并且注册成springBean,它是Mybits启动所必须的sql会话工厂
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(dataSource);
...
return factory.getObject();
}
}
额外补充,可忽略:条件开关可以分为多种:
@ConditionalOnBean:当容器里有指定Bean的条件下
@ConditionalOnClass:当类路径下有指定的类的条件下
@ConditionalOnExpression:基于SpEL表达式为true的时候作为判断条件才去实例化
@ConditionalOnJava:基于JVM版本作为判断条件
@ConditionalOnJndi:在JNDI存在的条件下查找指定的位置
@ConditionalOnMissingBean:当容器里没有指定Bean的情况下
@ConditionalOnMissingClass:当容器里没有指定类的情况下
@ConditionalOnWebApplication:当前项目时Web项目的条件下
@ConditionalOnNotWebApplication:当前项目不是Web项目的条件下
@ConditionalOnProperty:指定的属性是否有指定的值
@ConditionalOnResource:类路径是否有指定的值
@ConditionalOnOnSingleCandidate:当指定Bean在容器中只有一个,或者有多个但是指定首选的Bean
配置属性类MybitsProperties.class的成员变量可以在Spring-Boot项目中的resource/application.yml或是application.priperties的外化配置文件中通过打印前缀关键字进行设置
小结
自动配置流程:META-INF/spring.factories---> MybatisAutoConfigraution---> MybatisPropeties (prefix )---> application.yml里的mybatis开头的所有配置
MybatisAutoConfigraution 负责自动配置
MybatisPropeties 存储外化配置数据
自定义starter
1.开发快递鸟
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
public class KuaiDiNiaoQueryAPI {
* ID和Key请到官网申请:http://www.kdniao.com/ServiceApply.aspx
//电商ID 我的用户名
private String EBusinessID;
//电商加密私钥,快递鸟提供,注意保管,不要泄漏
private String AppKey;
//请求url
private String ReqURL;
public KuaiDiNiaoQueryAPI(ExprsTrackConfig config){
this.EBusinessID=config.getUserKey();
this.AppKey=config.getUserSecret();
this.ReqURL=config.getApiUrl();
}
/**
* Json方式 查询订单物流轨迹
* @param expCode 物流公司的编码
* @param expNo 物流号
* @return 查询结果
* @throws Exception
*/
public String getOrderTracesByJson(String expCode, String expNo) throws Exception{
String requestData= "{'OrderCode':'','ShipperCode':'" + expCode + "','LogisticCode':'" + expNo + "'}";
Map<String, String> params = new HashMap<String, String>();
params.put("RequestData", urlEncoder(requestData, "UTF-8"));
params.put("EBusinessID", EBusinessID);
params.put("RequestType", "1002");
String dataSign=encrypt(requestData, AppKey, "UTF-8");
params.put("DataSign", urlEncoder(dataSign, "UTF-8"));
params.put("DataType", "2");
String result=sendPost(ReqURL, params);
//根据公司业务处理返回的信息......
return result;
}
/**
* MD5加密
* @param str 内容
* @param charset 编码方式
* @throws Exception
*/
@SuppressWarnings("unused")
private String MD5(String str, String charset) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes(charset));
byte[] result = md.digest();
StringBuffer sb = new StringBuffer(32);
for (int i = 0; i < result.length; i++) {
int val = result[i] & 0xff;
if (val <= 0xf) {
sb.append("0");
}
sb.append(Integer.toHexString(val));
}
return sb.toString().toLowerCase();
}
/**
* base64编码
* @param str 内容
* @param charset 编码方式
* @throws UnsupportedEncodingException
*/
private String base64(String str, String charset) throws UnsupportedEncodingException {
String encoded = base64Encode(str.getBytes(charset));
return encoded;
}
@SuppressWarnings("unused")
private String urlEncoder(String str, String charset) throws UnsupportedEncodingException{
String result = URLEncoder.encode(str, charset);
return result;
}
/**
* 电商Sign签名生成
* @param content 内容
* @param keyValue Appkey
* @param charset 编码方式
* @throws UnsupportedEncodingException ,Exception
* @return DataSign签名
*/
@SuppressWarnings("unused")
private String encrypt (String content, String keyValue, String charset) throws UnsupportedEncodingException, Exception
{
if (keyValue != null)
{
return base64(MD5(content + keyValue, charset), charset);
}
return base64(MD5(content, charset), charset);
}
/**
* 向指定 URL 发送POST方法的请求
* @param url 发送请求的 URL
* @param params 请求的参数集合
* @return 远程资源的响应结果
*/
@SuppressWarnings("unused")
private String sendPost(String url, Map<String, String> params) {
OutputStreamWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
HttpURLConnection conn =(HttpURLConnection) realUrl.openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// POST方法
conn.setRequestMethod("POST");
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.connect();
// 获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
// 发送请求参数
if (params != null) {
StringBuilder param = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if(param.length()>0){
param.append("&");
}
param.append(entry.getKey());
param.append("=");
param.append(entry.getValue());
//System.out.println(entry.getKey()+":"+entry.getValue());
}
//System.out.println("param:"+param.toString());
out.write(param.toString());
}
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result.toString();
}
private static char[] base64EncodeChars = new char[] {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/' };
public static String base64Encode(byte[] data) {
StringBuffer sb = new StringBuffer();
int len = data.length;
int i = 0;
int b1, b2, b3;
while (i < len) {
b1 = data[i++] & 0xff;
if (i == len)
{
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
sb.append("==");
break;
}
b2 = data[i++] & 0xff;
if (i == len)
{
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
sb.append("=");
break;
}
b3 = data[i++] & 0xff;
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
sb.append(base64EncodeChars[b3 & 0x3f]);
}
return sb.toString();
}
}
//配置类
public class ExprsTrackConfig {
/**
* 用户key
*/
private String userKey;
/**
* 用户密码
*/
private String userSecret;
/**
* 请求地址
*/
private String apiUrl;
public String getUserKey() {
return userKey;
}
public void setUserKey(String userKey) {
this.userKey = userKey;
}
public String getUserSecret() {
return userSecret;
}
public void setUserSecret(String userSecret) {
this.userSecret = userSecret;
}
public String getApiUrl() {
return apiUrl;
}
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
}
}
//配置属性类
public class App
{
public static void main(String[] args) throws Exception {
ExprsTrackConfig config = new ExprsTrackConfig();
config.setApiUrl("http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx");
config.setUserKey("自行申请注册");
config.setUserSecret("自行申请注册");
KuaiDiNiaoQueryAPI api = new KuaiDiNiaoQueryAPI(config);
String yzpy = api.getOrderTracesByJson("SF", "单号");
System.out.println(yzpy);
}}
2. 将kuaidiniao打包安装到本地仓库 mvn clean install
3.开发kuaidniao-spring-boot-starter,加依赖
<properties>
<spring-boot.version>2.5.3</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 自定义boot-starter必须有的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>${spring-boot.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.woniuxy.class58</groupId>
<artifactId>kuaidiniao</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
4.创建spring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=KuaiDiNiaoAutoConfiguration类路径
5.开发自动配置类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(KuaiDiNiaoProperties.class)
public class KuaiDiNiaoAutoConfiguration {
@Autowired
private KuaiDiNiaoProperties kuaiDiNiaoProperties;
@Bean
public KuaiDiNiaoQueryAPI kuaiDiNiaoQueryAPI(){
ExprsTrackConfig config = new ExprsTrackConfig();
//读取外化配置,并将赋给相应的属性
config.setApiUrl(kuaiDiNiaoProperties.getApiUrl());
config.setUserKey(kuaiDiNiaoProperties.getUserKey());
config.setUserSecret(kuaiDiNiaoProperties.getUserSecret());
KuaiDiNiaoQueryAPI kuaiDiNiaoQueryAPI = new KuaiDiNiaoQueryAPI(config);
return kuaiDiNiaoQueryAPI;
}
}
6.开发属性类
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "kuaidiniao")
public class KuaiDiNiaoProperties {
private String apiUrl;
private String userKey;
private String userSecret;
public String getApiUrl() {
return apiUrl;
}
public void setApiUrl(String apiUrl) {
this.apiUrl = apiUrl;
}
public String getUserKey() {
return userKey;
}
public void setUserKey(String userKey) {
this.userKey = userKey;
}
public String getUserSecret() {
return userSecret;
}
public void setUserSecret(String userSecret) {
this.userSecret = userSecret;
}
@Override
public String toString() {
return "KuaiDiNiaoProperties{" +
"apiUrl='" + apiUrl + '\\'' +
", userKey='" + userKey + '\\'' +
", userSecret='" + userSecret + '\\'' +
'}';
}
}
7.安装快递鸟starter mvn clean install
8.在Spring-Boot项目中测试,添加starter依赖,并以前缀关键字添加属性
9.Test
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import query.KuaiDiNiaoQueryAPI;
import javax.annotation.Resource;
@Controller
public class KuaiDiNiaoQuery {
@Resource
private KuaiDiNiaoQueryAPI kuaiDiNiaoQueryAPI;
@RequestMapping("/query")
//将javaBean转为json输出并在前端页面打印
@ResponseBody
public String query(String kd, String no) throws Exception {
return kuaiDiNiaoQueryAPI.getOrderTracesByJson(kd,no);
}
}
总结图
以上是关于浅析SpringBoot自动配置的原理及实现的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot自动配置原理及如何创建自己的Starter