基于spring boot排除扫描类的三种方式小结
最近在做单测的时候,由于自己配置的spring boot容器会默认扫描很多不想被加载,网上中文的文章并不多,所以来总结一下。
默认下面描述的类都在一个包下面第一步我们新建一个应用启动的类,一个类用来充当Configuration,为了能明显的感知到其到底有没生效,我编写如下:
@SpringBootApplicationpublic class Test { public static void main(String[] args) {new SpringApplication(Test.class).run(args); }}
@Configurationpublic class MyConfig { @Bean public BeanPostProcessor beanPostProcessor() {System.out.println('初始化了 bean BeanPostProcessor');return new BeanPostProcessor() { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {System.out.println('加载了bean ' + beanName);return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {return bean; }}; }}
我们可以启动应用发现输出
初始化了 bean BeanPostProcessor加载了bean org.springframework.context.event.internalEventListenerProcessor加载了bean org.springframework.context.event.internalEventListenerFactory加载了bean org.springframework.boot.autoconfigure.AutoConfigurationPackages加载了bean org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration加载了bean org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration加载了bean objectNamingStrategy加载了bean mbeanServer加载了bean mbeanExporter加载了bean org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration加载了bean spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties加载了bean org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration加载了bean org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration
说明被@Configuration 修饰的类MyConfig本身被扫描了。
方法1:用exclude指明明确要排除的类.@SpringBootApplication@ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {MyConfig.class})})public class Test { public static void main(String[] args) {new SpringApplication(Test.class).run(args); }}
用ComponentScan的excludeFilters属性,可以明确排除调需要扫描的类。
但是这里存在一个问题,如果要排除的类比较多,那这里会看起来很冗余。我们可以采用第二种方式。注解排除。
方法2 : 用注解方式排除public @interface IgnoreScan {}
新建此注解。
在需要忽略的类上添加:
@Configuration@IgnoreScanpublic class MyConfig { @Bean public BeanPostProcessor beanPostProcessor() {System.out.println('初始化了 bean BeanPostProcessor');return new BeanPostProcessor() { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {System.out.println('加载了bean ' + beanName);return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {return bean; }}; }}
这样即可排除掉不被扫描了。
方法3 :第三种方式实现org.springframework.core.type.filter.TypeFilter,然后也是ComponentScan去排除指定的注解。网上写的好的文章很多,这里不多说了。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持好吧啦网。
相关文章:
1. 怎样才能用js生成xmldom对象,并且在firefox中也实现xml数据岛?2. ASP删除img标签的style属性只保留src的正则函数3. asp(vbs)Rs.Open和Conn.Execute的详解和区别及&H0001的说明4. 《CSS3实战》笔记--渐变设计(一)5. html5手机触屏touch事件介绍6. CTF中的PHP特性函数解析之下篇7. 页面遮罩层,并且阻止页面body滚动。bootstrap模态框原理8. XML实体注入深入理解9. npm报错:无法将"npm"项识别为cmdlet、函数、脚本文件或可运行程序的名称10. 存储于xml中需要的HTML转义代码

网公网安备