@Component 和 @ComponentScan 的区别
1、springboot 项目
如果你的其他包都在使用了@SpringBootApplication注解的main
app所在的包及其下级包,则你什么都不用做,SpringBoot会自动帮你把其他包都扫描了
如果你有一些bean所在的包,不在main
app的包及其下级包,那么你需要手动加上@ComponentScan注解并指定那个bean所在的包
2、spring项目
2.1 xml中配置 标签
<context:component-scan base-package="com.ali"/>
2.2 配置类中添加扫面的路径
@Configuration @ComponentScan("com.ali") public class MainConfig { }
3、代码链接
见文件中的springDemo
4、ComponentScan排除和指定某些类
4.1 只扫描某些类
/** * 子容器 * SpringMVC只扫描Controller * 必须设置useDefaultFilters=false 必须禁用默认的过滤规则 * includeFilters 意思是扫描的时候只扫描某些类型,根据注解来扫描,扫描那些用@Controller注解的类,并且禁用掉默认的。 */ @ComponentScan(value = "com.gts.sofa",includeFilters = {@ComponentScan.Filter(type= FilterType.ANNOTATION,classes = {Controller.class})}, useDefaultFilters = false) public class AppConfig extends WebMvcConfigurerAdapter { //定制视图解析器 这里配置的路径不是resource下面的,是web目录下面的 @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/WEB-INF/views/",".jsp"); } }
4.2 排除某些类
/** * * excludeFilters 指定那些不要扫描必须传一些Filter数组 type是指定按照那些规则来排除,这个根据注解来排除,标注了@Controller注解的类不扫描 */ @ComponentScan(value = "com.gts.sofa",excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class})}) public class RootConfig { }