Spring Boot自动装配
1.程序入口
package com.kuang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootStudyApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootStudyApplication.class, args);
}
}
2.@SpringBootApplication注解
@SpringBootApplication:spring boot应用标注在某个类上说明这个类是SpringBoot的主配置类,SpringBoot就应该运行这个类的main方法来启动SpringBoot应用;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration //配置类注解
@EnableAutoConfiguration //开启自动装配
@ComponentScan( //扫描组件
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
@SpringBootApplication是一个复合型注解,由@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan组成
2.1 @SpringBootConfiguration
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration //配置类注解
public @interface SpringBootConfiguration {
@AliasFor(
annotation = Configuration.class
)
boolean proxyBeanMethods() default true;
}
@SpringBootConfiguration:标注在某个类上,表示这是一个SpringBoot的配置类;
主要由@Configuration组成,
@Configuration:配置类上标注这个注解;
2.2 @EnableAutoConfiguration
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage //自动配置包
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
@EnableAutoConfiguration:开启自动装配
@AutoConfigurationPackage :自动配置包
@Import(AutoConfigurationPackages.Registrar.class):
Spring的底层注解@import,给容器导入一个组件,导入的组件为AutoConfigurationPackages.Registrar.class;
SpringFactoriesLoader 类会去寻找 项目依赖jar中的/META-INF/spring.factories文件中的配置
2.3 @ComponentScan
@ComponentScan:组件扫描注解
扫描启动类所在包的所有组件
3.结论
SpringBoot不需要写配置文件的原因是,SpringBoot所有配置都是在启动的时候进行扫描并加载,SpringBoot的所有自动配置类都在Spring.factories里面,但是不一定会生效,生效前要判断条件是否成立,只要导入了对应的start,就有对应的启动器,有了启动器就能帮我们进行自动配置类