SpringBoot中怎样的类才能被称为auto-configuration classes?

查看:292
本文介绍了SpringBoot中怎样的类才能被称为auto-configuration classes?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

  1. 今天尝试在SpringBootApplication标签中使用exclude去排除一个class,让这个class不加载。但是一直没有成功。
    然后看源码中exclude与excludeName中有个注释

Exclude specific auto-configuration classes

于是在class中加上诸如
@EnableAutoConfiguration
@AutoConfigureAfter
之类的注释,然而还是没有啥用。
所以想请教大神们,怎么样的类可以被称为auto-configuration classes
让它可以被exclude排除掉。

  1. 部分代码如下

@SpringBootApplication(scanBasePackages = "com",
    exclude = com.MybatisConfig.class)
@EnableFeignClients
@EnableEurekaClient
public class Application {

@Configuration
@AutoConfigureAfter(MyAppConfig.class)
@EnableTransactionManagement
@MapperScan({"com.**.dao"})
public class MybatisConfig {

解决方案

其实spring 加载bean只有一个方法,那就是在默认扫描包路径的下如:@ComponentScan(basePackages = "com")
则会扫描路径下的所有bean。
然后spring boot增加了一种加载bean的方法,那就是auto-configuration。这种auto-configuration并不会存在于扫描包的路径下(存在就是正常bean了)。它们的加载方式是jar包中的META-INF/spring.factories。
Spring boot是如何去读取此文件的并没有详细的了解。

根据实验和源码,得到的结论是
1、存在于META-INF/spring.factories配置中。
2、不在componentScan扫描包的范围内。
这些bean被可以被认为是auto-configuration。

解决了题目的问题。下面是解决引申的问题
@SpringBootApplication中的exclude可以过滤掉auto-configuration
那么正常bean怎么exclude掉呢?
目前看到的方法是使用@ComponentScan中的excludeFilters
示例代码如下

@ComponentScan(basePackages = "com", excludeFilters = @Filter(
    type = FilterType.REGEX,
    pattern = "com.TestClass"
))

不要被我的pattern 迷惑,这里是写正则表达式的。
方式很多,主要根据是FilterType
spring-boot 1.4.2版本中FilterType有ANNOTATION,ASSIGNABLE_TYPE,ASPECTJ,REGEX,CUSTOM
应该能满足大部分需求。
比如我就打算自己写一个FilterType.CUSTOM的Filter去做这个事情。

这篇关于SpringBoot中怎样的类才能被称为auto-configuration classes?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆