-
使用IncludeFilter。就算目标类上没有@Component注解,它也会被扫描成为一个Bean
@ComponentScan(value = "com.yzy", includeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {OtherEntity.class})}) @MapperScan(basePackages = "com.yzy.springdemo.dao") @EnableAspectJAutoProxy public class SpringAnnotationTest { }public class OtherEntity { }public class Test { public static void main(String[] args) throws IOException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringAnnotationTest.class); OtherEntity otherEntity = (OtherEntity) context.getBean("otherEntity"); System.out.println(otherEntity);//com.yzy.other.OtherEntity@5769e7ae } } -
使用ExcludeFilter,就算目标类上面有@Component注解也不会成为Bean
@Component public class OtherEntity { }@ComponentScan(value = "com.yzy", excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,classes = {OtherEntity.class})}) @MapperScan(basePackages = "com.yzy.springdemo.dao") @EnableAspectJAutoProxy public class SpringAnnotationTest { }public class Test { public static void main(String[] args) throws IOException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringAnnotationTest.class); OtherEntity otherEntity = (OtherEntity) context.getBean("otherEntity"); System.out.println(otherEntity); } }运行项目:

spring使用ExcludeFilter和IncludeFilter
最新推荐文章于 2025-01-13 10:13:28 发布
本文详细介绍了Spring中@ComponentScan注解的使用,包括如何通过IncludeFilter包含特定类作为Bean,即使该类未标记为@Component。同时,也展示了如何使用ExcludeFilter排除已经标记为@Component的类不被扫描为Bean。示例代码展示了这两种过滤机制的实际应用。
804

被折叠的 条评论
为什么被折叠?



