GITHUB地址:https://github.com/zhangboqing/springboot-learning

一、Spring Boot自动配置原理

  自动配置功能是由@SpringBootApplication中的@EnableAutoConfiguration注解提供的。

 @Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration { String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; /**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class<?>[] exclude() default {}; /**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
String[] excludeName() default {}; }

  这里的关键功能是@Import(AutoConfigurationImportSelector.class),它导入了AutoConfigurationImportSelector类,该类使用了SpringFactoriesLoader.loadFactoryNames方法来扫描具有META-INF/spring.factories文件的jar包。

 protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
Assert.notEmpty(configurations,
"No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}

  并且在META-INF/spring.factories中定义了需要自动配置的具体类是什么

 org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.zbq2.autoconfig.HelloServiceAutoConfiguration

二、如何实现自动配置功能

1.新建stater maven项目
增加Spring Boot自身的自动配置maven依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>

2.属性配置
HelloServiceProperties
自定义一个获取属性的类,可以获取在application.properties中设置的自定义属性

 /**
* @author zhangboqing
* @date 2018/6/29
*/
@Data
@ConfigurationProperties(prefix = "hello")
public class HelloServiceProperties { private static final String MSG = "world"; private String msg = MSG;
}

3.判断依据类
HelloService
定义一个类,通过判断该类是否存在,来创建该类的Bean,该类可以是第三方库的类如DataSource

 /**
* @author zhangboqing
* @date 2018/6/29
*/
@Data
public class HelloService { private String msg; public String sayHello() {
return new StringBuilder("Hello").append(msg).toString();
}
}

4.自动配置类
HelloServiceAutoConfiguration
根据HelloServiceProperties提供的参数,并通过@ConditionalOnClass判断HelloService这个类在类路径中是否存在,且当容器中没有这个Bean的情况下自动配置这个Bean

 /**
* @author zhangboqing
* @date 2018/6/29
*/
@Configuration
@EnableConfigurationProperties(HelloServiceProperties.class)
@ConditionalOnClass(HelloService.class)
@ConditionalOnProperty(prefix = "hello",matchIfMissing = true)
public class HelloServiceAutoConfiguration { @Autowired
private HelloServiceProperties helloServiceProperties; @Bean
@ConditionalOnMissingBean(HelloService.class)
public HelloService helloService() {
HelloService helloService = new HelloService();
helloService.setMsg(helloServiceProperties.getMsg());
return helloService;
} }

5.注册配置
若想自动配置生效,需要注册自动配置类。在src/main/resources下新建META-INF/spring.factories
如下:

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration

若有多个自动配置,则用','隔开,此处'\'是为了换行后仍能读到属性

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.zbq2.autoconfig.HelloServiceAutoConfiguration

6.使用starter 作为其他项目的依赖
引入maven 坐标依赖

Spring Boot之实现自动配置的更多相关文章

  1. 学记:为spring boot写一个自动配置

    spring boot遵循"约定优于配置"的原则,使用annotation对一些常规的配置项做默认配置,减少或不使用xml配置,让你的项目快速运行起来.spring boot的神奇 ...

  2. 4、Spring Boot 2.x 自动配置原理

    1.4 Spring Boot 自动配置原理 简介 spring boot自动配置功能可以根据不同情况来决定spring配置应该用哪个,不应该用哪个,举个例子: Spring的JdbcTemplate ...

  3. Spring Boot面试杀手锏————自动配置原理

    转:https://blog.csdn.net/u014745069/article/details/83820511 引言不论在工作中,亦或是求职面试,Spring Boot已经成为我们必知必会的技 ...

  4. Spring Boot框架的自动配置

    (图片来源于网络,侵删!!!) l  @RestController 因为我们例子是写一个web应用,因此写的这个注解,这个注解相当于同时添加@Controller和@ResponseBody注解 l ...

  5. SpringBoot 源码解析 (五)----- Spring Boot的核心能力 - 自动配置源码解析

    在上一篇博客中分析了springBoot启动流程,大体的轮廓只是冰山一角.今天就来看一下springBoot的亮点功能:自动化装配功能. 先从@SpringBootApplication开始.在启动流 ...

  6. 006-Spring Boot自动配置-Condition、Conditional、Spring提供的Conditional自动配置

    一.接口Condition.Conditional(原理) 主要提供一下方法 boolean matches(ConditionContext context, AnnotatedTypeMetada ...

  7. spring boot(5)-properties参数配置

     application.properties application.properties是spring boot默认的配置文件,spring boot默认会在以下两个路径搜索并加载这个文件 s ...

  8. Spring Boot 支持多种外部配置方式

    Spring Boot 支持多种外部配置方式 http://blog.csdn.net/isea533/article/details/50281151 这些方式优先级如下: 命令行参数 来自java ...

  9. Spring Boot 项目学习 (四) Spring Boot整合Swagger2自动生成API文档

    0 引言 在做服务端开发的时候,难免会涉及到API 接口文档的编写,可以经历过手写API 文档的过程,就会发现,一个自动生成API文档可以提高多少的效率. 以下列举几个手写API 文档的痛点: 文档需 ...

随机推荐

  1. topcoder srm 505 div1

    problem1 link 设行数为$n$列数为$m$ 对于任意的两行$r_{1},r_{2}$以及任意的两列$c_{1},c_{2}$所确定的四个格子,只要知道其中的三个就能确定第四个,且必须要三个 ...

  2. 运行django新的项目,页面总是显示以前的项目,问题解决

    运行django新的项目,页面总是显示以前的项目 只需打开任务管理器,再进程中关闭python.exe 再次重新启动服务,python manage.py runserver.即可

  3. 总结: 在fc23中, 安装音频mp3 视频flv 的播放插件其实很简单, 只要一步就可以了: dnf install gstreamer1-libav

    同样是 firefox, 单词的在线发音, 跟 百度mp3的在线播放不是一样的!!! 百度/优酷 的在线播放, 用的确实是 flash player , 所以 你安装好libflashplayer后, ...

  4. 【做题】agc006C - Rabbit Exercise——模型转换

    原文链接https://www.cnblogs.com/cly-none/p/9745177.html 题意:数轴上有\(n\)个点,从\(1\)到\(n\)编号.有\(m\)个操作,每次操作给出一个 ...

  5. C# 禁止任务管理器关闭

    http://www.cnblogs.com/luomingui/archive/2011/06/25/2090130.html 测试了好像没用的.不知道什么原因

  6. 论文笔记之:Deep Attributes Driven Multi-Camera Person Re-identification

    Deep Attributes Driven Multi-Camera Person Re-identification 2017-06-28  21:38:55    [Motivation] 本文 ...

  7. VHDL 乐曲演奏电路设计

    前言 无源蜂鸣器在直流信号下不会响,需要方波驱动.输入不同频率的方波会发出不同音调的声音,方波的幅值决定了声音的响度. 目标 乐曲发生电路在节拍(4Hz)的控制下根据乐谱产生合适的分频系数.分频器根据 ...

  8. 在服务器端对sshd做白名单

    1.添加用户 #useradd aaa #passwd aaa -->输入密码:123456 添加3个用户,bbb和ccc与aaa添加一样 2.添加白名单 #vim /etc/ssd/sshd_ ...

  9. HDU 4309 Seikimatsu Occult Tonneru(最大流+二进制枚举)

    http://acm.hdu.edu.cn/showproblem.php?pid=4309 题意: 有n个城市,每个城市有num[i]个居民,有敌人要进行地毯式轰击,居民们要逃到隧道去.现在有隧道, ...

  10. oracle 与其他数据库如mysql的区别

    想明白一个问题:(1)oracle是以数据库为中心,一个数据库就是一个域(可以看作是一个文件夹的概念),一个数据库可以有多个用户,创建用户是在登陆数据库之后进行的,但是有表空间的概念(2)而mysql ...