SpringBootApplication的原理

[TOC]

进入到@SpringBootApplication的源码,可以看到里面组合了三个我们感兴趣的注解:@ComponentScan,@EnableAutoConfiguration,@SpringBootConfiguration.我们一一分析这三个注解.

2.1@ComponentScan

使用过spring框架的小伙伴都知道,spring里有四大注解:@Service,@Repository,@Component,@Controller用来定义一个bean.@ComponentScan注解就是用来自动扫描被这些注解标识的类,最终生成ioc容器里的bean.可以通过设置@ComponentScan basePackages,includeFilters,excludeFilters属性来动态确定自动扫描范围,类型已经不扫描的类型.默认情况下:它扫描所有类型,并且扫描范围是@ComponentScan注解所在配置类包及子包的类,在hello word 工程里,添加了一个componentscan 分支,说明这个情况.QuickStartApplication,CurrentPackageController类的package是com.simos.componentscanSubPackageController的package 是com.simos.componentscan.controller.而OutPackageController的package是com.simos.controller.启动后只有:SubPackageControllerCurrentPackageController被扫描生成bean,而OutPackageController却没有被扫描到.下面三个截图说明了这一点:

img

current.png

img

sub.png

img

out.png

总结一下,使用@SpringBootApplication注解,就说明你使用了@ComponentScan的默认配置,这就建议你把使用@SpringBootApplication注解的类放置在root package(官方表述)下,其他类都置在root package的子包里面,这样bean就不会被漏扫描.

2.2@SpringBootConfiguration

这个注解的作用与@Configuration作用相同,都是用来声明当前类是一个配置类.可以通过@Bean注解生成IOC容器管理的bean.在QuickStartApplication中定义bean,并在@HelloController中注入使用

1
2
3
4
5
6
7
8
9
10
@SpringBootApplication
public class QuickStartApplication {
public static void main(String[]args){
SpringApplication.run(QuickStartApplication.class,args);
}
@Bean
public BeanTest beanTest(){
return new BeanTest();
}
}

下面是@HelloController

1
2
3
4
5
6
7
8
9
10
11
12
13
@RestController
public class HelloController {
@Autowired
BeanTest beanTest;
@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String hello(){
return "hello world!";
}
@RequestMapping(value = "/beantest",method = RequestMethod.GET)
public String beanTest(){
return "beanTest!";
}
}

2.3@EnableAutoConfiguration

@EnableAutoConfiguration是springboot实现自动化配置的核心注解,通过这个注解把spring应用所需的bean注入容器中.@EnableAutoConfiguration源码通过@Import注入了一个ImportSelector的实现类