(一)、Spring Boot之@SpringBootApplication注解的理解

一、spring boot启动的main方法上必须要有的注解@SpringBootApplication

@SpringBootApplication
public class SpringBootDemoApplication {

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

}

1.1、@SpringBootApplication注解

请看@SpringBootApplication注解的源码:

@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}
)}
)
public @interface SpringBootApplication {

由此可见@SpringBootApplication注解是个组合注解,由三个元注解组合而成:

@SpringBootConfiguration(实际上就是@Configuration):表示当前的启动类时一个配置类,可以在这个类中通过@Bean注解     来自定义bean,依赖关系等。

@EnableAutoConfiguration:借助@Import这个注解将所有符合自动配置条件的bean定义加载到Ioc容器。

@ComponentScan:spring的自动扫描注解,可定义扫描包范围,加载到Ioc容器中。

1.1.1、@ComponentScan注解

            该注解就相当于xml配置文件中的<context:component-scan base-package="com.test"/> ,主要就是用来定义扫描的路径,从该扫描的路径中找出标识了需要装配的类自动装配到spring的Ioc容器中(也就是说spring会扫描具有特殊注解的Java类,然后把这些类对象添加应用上下文中配置为bean)。

特殊注解有:

(1)、@Component通用的注解;

(2)、@Controller标识了该类定义为Spring MVC的Controller;

(3)、@Repository标识了该类定义为数据库;

(4)、@Service标识了该类定义为服务;

(5)、使用了@Component作为元注解的自定义类;

(6)、自定义扫描配置类:用@Configuration标注的类并且在该类中有使用@Bean注解标注的方法。

1.1.2、@EnableAutoConfiguration注解

     先来看一下@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 {};
}

其中最核心的就是@Import({AutoConfigurationImportSelector.class}),继续看AutoConfigurationImportSelector.class的源码:

(1)、loadMetadata加载配置:438条配置属性

其实就是用类加载器去加载:META-INF/spring-autoconfigure-metadata.properties(spring-boot-autoconfigure-1.5.9.RELEASE-sources.jar)文件中定义的配置,返回PropertiesAutoConfigurationMetadata(实现了AutoConfigurationMetadata接口,封装了属性的get set方法)

(2)、getCandidateConfigurations获取默认支持的自动配置类名列表:97个自动配置类

自动配置灵魂方法,SpringFactoriesLoader.loadFactoryNames 从META-INF/spring.factories(spring-boot-autoconfigure-1.5.9.RELEASE-sources.jar)文件中获取自动配置类key=EnableAutoConfiguration.class的配置。

实际获取了spring.factories文件中的#Auto Configure中=后面的自动匹配之类。

(3)、filter过滤器 根据OnClassCondition注解把不满足条件的过滤掉

          

猜你喜欢

转载自blog.csdn.net/hdn_kb/article/details/91806462