Spring Boot的@SpringBootApplication、@EnableAutoConfiguration、@ComponentScan注解

Spring Boot的@SpringBootApplication、@EnableAutoConfiguration、@ComponentScan注解,我经常在启动类上傻傻分不清,


@EnableAutoConfiguration这个注解是是Springboot根据我们所引入的jar包自动配置的,假设我们有自己的配置类则会覆盖


@ComponentScan是告诉springboot进行包扫描的


而@SpringBootApplication注解等价于以默认属性使用@Configuration,@EnableAutoConfiguration和@ComponentScan


以下摘自Springboot官方文档:

很多Spring Boot开发者经常使用@Configuration@EnableAutoConfiguration@ComponentScan注解他们的main类,由于这些注解如此频繁地一块使用(特别是遵循以上[最佳实践](14. Structuring your code.md)的时候),Spring Boot就提供了一个方便的@SpringBootApplication注解作为代替。

@SpringBootApplication注解等价于以默认属性使用@Configuration@EnableAutoConfiguration@ComponentScan

package com.example.myproject;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {

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

}

@SpringBootApplication注解也提供了用于自定义@EnableAutoConfiguration@ComponentScan属性的别名(aliases)。

你可能感兴趣的:(spring-boot)