• Spring Boot核心注解@SpringBootApplication


    一、作用

      @SpringBootApplication是一个组合注解,用于快捷配置启动类。

    二、用法

      可配置多个启动类,但启动时需选择以哪个类作为启动类来启动项目。

    三、拆解

    1.拆解

       此注解等同于@Configuration+@EnableAutoConfiguration+@ComponentScan的合集,详见https://docs.spring.io/spring-boot/docs/1.5.5.BUILD-SNAPSHOT/reference/htmlsingle/#using-boot-using-springbootapplication-annotation

    2.源码

      查看@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 {
    3.源码分析

    前四个注解是元注解,用来修饰当前注解,就像public类的修饰词,无实际功能。后三个注解是真正起作用的注解,下面逐一解释。

    @SpringbootConfiguration

      说明这是一个配置文件类,它会被@ComponentScan扫描到。进入@SpringBootConfiguration源码发现它相当于@Configuration,借此讲解下。
      提到@Configuration就要提到他的搭档@Bean。使用这两个注解就可以创建一个简单的Spring配置类,可用来替代相应的xml配置文件。

    @Configuration  
    public class Conf {  
        @Bean  
        public Car car() {  
            Car car = new Car();  
            car.setWheel(wheel());  
            return car;  
        }  
        @Bean   
        public Wheel wheel() {  
            return new Wheel();  
        }  
    }  

    等价于

    <beans>  
        <bean id = "car" class="com.test.Car">  
            <property name="wheel" ref = "wheel"></property>  
        </bean>  
        <bean id = "wheel" class="com.test.Wheel"></bean>  
    </beans>  

    @Configuration的注解类标识这个类可使用Spring IoC容器作为bean定义的来源。@Bean注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,该对象被注册为在Spring应用程序中上下文的bean。

    @ComponentScan

      会自动扫描指定包下全部标有@Component的类,并注册成bean,当然包括@Component下的子注解:@Service,@Repository,@Controller;默认会扫描当前包和所有子包。

    @EnableAutoConfiguration

      根据类路径中jar包是否存在来决定是否开启某一个功能的自动配置。

    tips:exclude和excludeName用于关闭指定的自动配置,比如关闭数据源相关的自动配置

    Reference:
    https://www.jianshu.com/p/53a2df2233ce

  • 相关阅读:
    前端模板Nunjucks简介
    git提交时支持文件名大小写的修改
    多行文本加省略号的处理方法
    前端性能优化实践方案总结
    使用gulp工具生成svgsprites
    koa简介
    JSX语法简介
    踩坑所引发出的appendChild方法的介绍
    React业务实践
    javascript--数组
  • 原文地址:https://www.cnblogs.com/east7/p/10426832.html
Copyright © 2020-2023  润新知