SpringBoot核心原理:自动配置
2018-02-25 java4all java4all
摘要:本文通过断点追溯源码的方式,来逐步展示SpringBoot的核心功能实现原理:自动化配置;
由于是分析源码,贴出了一些源码,所以文章较长,但关键都是在文字上,可以跳着看;
本文较长,分为两篇,但主要内容如下:
分析@SpringBootApplication源码;
分析@EnableAutoConfiguration源码;
分析AutoConfigurationImportSelector类中的部分方法(这个是关键);
(由于篇幅,我会删除很多无用代码,但不代表此类没有这些代码,如大量的import xxx.xxx.xxx等代码)
- 新建一个普通的SpringBoot项目,然后随便加几个注解,后面会提到这几个注解,代码如下:
package com.jd;
@EnableAsync
@RestController
@EnableScheduling
@SpringBootApplication
public class JdmallApplication {
public static void main(String[] args) {
SpringApplication.run(JdmallApplication.class, args);
}
@RequestMapping(value = "getHello",method = RequestMethod.GET)
public String getHello(){
return "good";
}
}
2.我们知道SpringBoot的入口是:@SpringBootApplication,我们进入这个注解,看看源码:
package org.springframework.boot.autoconfigure;
@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 {
@AliasFor(
annotation = EnableAutoConfiguration.class,
attribute = "exclude"
)
Class<?>[] exclude() default {};
@AliasFor(
annotation = EnableAutoConfiguration.class,
attribute = "excludeName"
)
String[] excludeName() default {};
@AliasFor(
annotation = ComponentScan.class,
attribute = "basePackages"
)
String[] scanBasePackages() default {};
@AliasFor(
annotation = ComponentScan.class,
attribute = "basePackageClasses"
)
Class<?>[] scanBasePackageClasses() default {};
}
公众号来源:java4all