浅谈SpringBoot自动装配

浅谈SpringBoot自动装配

说在前面

我们都知道Ioc和AOP是Spring的两大核心特性,而近年来随着SpringBoot的越来越“智能”化,开发人员使用SpringBoot的也越来越多,那SpringBoot帮我们做了什么,又有哪些特性呢?

SpringBoot的特性

  • 创建独立的Spring应用;
  • 直接嵌入Tomcat、Jetty或Undertow等Web容器(不需要部署WAR文件);
  • 提供固化的“starter”依赖,简化构建配置;
  • 当条件满足时自动装配Spring或第三方类库;
  • 提供运维特性,如指标信息(Metrics)、健康检查及外部化配置;
  • 绝无代码生成,并且不需要XML配置;

接下来,浅谈一下SpringBoot的自动装配特性(Auto-configuration)。

理解自动装配

官方文档介绍:

Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added.

从上面介绍可以看出,自动装配是有前提的,即取决于应用的Classpath下的JAR文件依赖,同时其自动装配的实体并非一定装载,所以文档中使用了“attempts”(尝试)来进行描述。

简单来说就是,举个例子,当HSQLDB存在于应用的Classpath中时,开发人员不需要手动配置数据库连接的Beans,而是由SpringBoot自动装配一个内存型的数据库Beans,开发人员可以直接使用。

官方文档介绍的激活自动装配的方法:

You need to opt-in to auto-configuration by adding the @EnableAutoConfiguration or @SpringBootApplication annotations to one of your @Configuration classes.

文档中提到激活自动化装配的注解@EnableAutoConfiguration和@SpringBootApplication,将两者选其一标注在@Configuration类上即可实现自动装配。

实现自动装配

<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-web</artifactId> </dependency> 
@SpringBootApplication public class AutoConfigurationBootStrap {    public static void main(String[] args) {  SpringApplication.run(AutoConfigurationBootStrap.class, args);  } } 

上面几行代码之后,你就可以成功运行一个Web服务,默认是Tomcat Server。

o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''

那么,SpringBoot是怎么实现这些的呢?答案在

浅谈SpringBoot自动装配

SpringBoot在启动的过程中,会加载META-INF/spring.factories里的某些类,注册成为对应的Bean。

SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,  this.getClass().getClassLoader()); 

通过上面这段代码就可以获取到META-INF/spring.factories定义的所有的装配类名(XxxAutoConfiguration),但是这些类不是所有都注册成为Bean,文章开头说了,只有在条件成立的情况下才会注册成为Bean,那需要什么条件呢?

org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration 

上面这个类在服务启动过程中,自动实现了相关WebServer的装配,

浅谈SpringBoot自动装配

我们可以看到,内嵌的Tomcat是需要某些条件(Condition)才能注册成为一个Bean,假如我们把相关类排除再启动看一下,

@EnableAutoConfiguration(exclude = ServletWebServerFactoryAutoConfiguration.class) public class AutoConfigurationBootStrap {  public static void main(String[] args) {  SpringApplication.run(AutoConfigurationBootStrap.class, args);  } 

浅谈SpringBoot自动装配

我们可以看到启动时出现异常。

总结:

从上面的文档简介或相关代码,可以看出SpringBoot的自动装配功能是通过 @EnableAutoConfiguration或@SpringBootApplication标注在某些类上,在服务启动过程中,会加载某一些类(META-INF/spring.factories)自动注册成为Bean,这样开发人员就无需写额外代码,就可以直接使用相关的Bean了。

您可能还会对下面的文章感兴趣: