我们上一篇文章新建了一个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