springboot和ssm之间最大的区别就在于它的自动配置,springboot自动配置原理也是springboot的精髓,可以说掌握了它就掌握了springboot的90%,便可以游刃有余的使用springboot,我来说说springboot的自动配置原理:
我们创建好一个springboot项目它是从这里开始执行的:
@SpringBootApplication
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
似乎没有什么特别之处,除了@SpringBootApplication注解,spirngboot的神奇能力正是由它带来的,我们看看这个注解:
@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 {
...
它上面又有很多注解,我们只看和自动配置有关的:@EnableAutoConfiguration注解,通过这个注解开启了springboot的自动配置:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
...
它上面有一个注解:@Import({AutoConfigurationImportSelector.class}),这个注解可以利用AutoConfigurationImportSelector扫描所有jar包类路径下的META-INF/spring.factories文件并且获取到文件中 EnableAutoConfiguration的值(也就是各种自动配置类),将他们放入spring容器中。
在spring-boot-autoconfigure中spring.factories文件如下
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
...
所有的以 AutoConfiguration为后缀的类的对象都被放入spring容器中,就是用他们来完成自动配置。
以HttpEncodingAutoConfiguration 为例看看它是如何完成自动配置:
@Configuration( //表示他是一个配置类
proxyBeanMethods = false
)
@EnableConfigurationProperties({HttpProperties.class})
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
prefix = "spring.http.encoding",
value = {"enabled"},
matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {
...