一、自动装配过程分析
关于@SpringBootApplication
@SpringBootApplication类本身是一个接口(@interface),内部含有@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan三个注解,其中:
①@SpringBootConfiguration
@SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类,并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到spring容器中,并且实例名就是方法名。
@SpringBootConfiguration可以理解为就是一个@Configuration注解, 表示当前类是一个配置类,通过@Configuration与@Bean结合,将@Bean注册到Spring ioc容器,@SpringBootConfiguration的源码中,除了@Target,@Retention,@Documented三个常规的注解外,最重要的注解是@Configuration。
@Configuration的作用:
从Spring3.0开始,@Configuration用于定义配置类,可替换xml文件,被注解的类中通常有一个或多个@Bean注解的方法,这些方法将会AnnotationConfigApplication或AnnotationConfigApplication类扫描,并用于构建@Bean定义,初始化Spring容器。
@Configuration标注在类上,@Configuration等价于spring的xml配置文件中的Beans节点。
②EnableAutoConfiguration
一旦加上此注解,那么就会开启自动装配功能。简单的说,Spring会在你的classpath下找到所有配置的Bean然后进行装配。当然,配置Bean时,会根据若干个(Conditional)定制规则来进行初始化。
其实 @EnableAutoConfiguration 注解也和其它 @Enable* 注解一脉相乘的,简单说一下就是借助 @Import 的支持,收集和注册特定场景相关的Bean的定义:比如:@EnableAspectJAutoProxy 就是通过@Import 注解动态的将Bean注册到 SpringIoc 容器中,而@EnableAutoConfiguration 是借助 @Import 把所有符合条件的 Bean 加载到 SpringIoc 容器中。
其中最重要的就是@Import(AutoConfigurationImportSelector.class)注解。借助AutoConfigurationImportSelector,@EnableAutoConfiguration帮助SpringBoot应用将所有符合条件的@Configuration配置加载到当前IoC容器中。而最主要的还是借助于Spring框架的一个工具类:SpringFactoriesLoader将META-INF/spring.factories加载配置,spring.factories文件是一个典型的properties配置文件,配置的格式仍然是key=value的形式,只不过key和value都是java的完整类名。比如:
org.springframework.data.repository.core.support.RepositoryFactorySupport=org.springframework.data.jpa.repository.support.JpaRepositoryFactory。
③@ComponentScan
@ComponentScan主要是定义扫描的路径从中找出了标识了需要装配的类自动装配到Spring的Bean容器中,如果没有指定包,因此他默认扫描与该类同级的类与同级包下的所有类。
@Controller,@Service,@Repositoty有一个共同的注解@Component。
@ComponentScan会默认会装配标识了@Controller,@Service,@Repository,@Component注解的类到Spring容器中。
自我理解:@SpringBootConfiguration用来标识@SpringBootApplication注解的类是一个配置类,而@EnableAutoConfiguration筛选需要装入SpringIoc的容器的配置,@ComponentScan用来扫描所有的业务Bean(@Controller,@Service,@Repository,包括被@Component注解的其他自定义注解)。