Spring系列-Spring boot启动原理

我们上一篇文章新建了一个Spring boot的项目:spring-boot-test,稍微做了一些配置就运行起来了。和以前运行普通的项目相比,Spring boot最大的特点就是没有那一堆的配置文件,而且不用配置Tomcat,直接就可以运行了。那Spring boot做了什么,可以让我们的开发变得这么方便呢?

还是要回到我们的项目中,我们的pom中引入了spring-boot-starter-web的依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

这个依赖就会引入内置的Tomcat,还有spring-webmvc。

接下来再看启动类:

@SpringBootApplication
public class SpringBootTestApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootTestApplication.class, args);
    }
}

上一篇文章说过,@SpringBootApplication是个组合注解,最主要的就是组合了@Configuration、@EnableAutoConfiguration、@ComponentScan这三个注解。

@Configuration声明当前类是一个配置类,相当于xml文件。@ComponentScan的功能是自动扫描需要装配的类,并自动装配到Spring的Bean容器中。
最重要的就是@EnableAutoConfiguration这个注解了,这个注解是进行自动配置的。我们启动Spring Boot项目的时候,这个注解就要起作用,根据我们引入的jar包,来自动的进行一些配置,省去了我们手动配置的麻烦。比如我们引入spring-boot-starter-web的依赖,就会自动的配置web项目中所需要的默认配置。

下面看下@EnableAutoConfiguration这个注解:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface 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 {};

}

在EnableAutoConfiguration中还定义了两个属性,exclude和excludeName,用来排除一些自动配置的类。

这里最关键的就是@Import(EnableAutoConfigurationImportSelector.class)。
@Import的作用是导入一个或多个配置类。
这里导入了EnableAutoConfigurationImportSelector,这是EnableAutoConfigurationImportSelector的图:
在这里插入图片描述

EnableAutoConfigurationImportSelector实现了ImportSelector接口,

public interface ImportSelector {

	/**
	 * Select and return the names of which class(es) should be imported based on
	 * the {@link AnnotationMetadata} of the importing @{@link Configuration} class.
	 */
	String[] selectImports(AnnotationMetadata importingClassMetadata);

}

ImportSelecto

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值