欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > Spring之@ComponentScan注解

Spring之@ComponentScan注解

2025/5/2 14:56:38 来源:https://blog.csdn.net/Rverdoser/article/details/141227693  浏览:    关键词:Spring之@ComponentScan注解

@ComponentScan 是一个Spring框架的注解,它的主要目的是为了让Spring框架能够找到自定义的组件,比如@Component和@Service等注解的类,并将它们注册为Spring应用上下文中的beans。

 @ComponentScan注解通常在配置类上使用,它会扫描指定的包及其子包下的所有类,查找标记了注解的类,并注册为bean。

以下是一些使用 @ComponentScan的方法:

基本使用方法:

@Configuration

@ComponentScan(basePackages = "com.example")

public class AppConfig {

}

在这个例子中,Spring将扫描"com.example"包及其子包。

使用basePackageClasses属性:

@Configuration

@ComponentScan(basePackageClasses = MyRepository.class)

public class AppConfig {

}

在这个例子中,Spring将扫描MyRepository类所在的包以及其子包。

使用filter属性:

@Configuration

@ComponentScan(basePackages = "com.example",

               includeFilters = @Filter(type = FilterType.ANNOTATION, classes = CustomAnnotation.class),

               excludeFilters = @Filter(type = FilterType.CUSTOM, classes = CustomExcludeFilter.class))

public class AppConfig {

}

在这个例子中,Spring将扫描"com.example"包及其子包中标记了CustomAnnotation的类,但会排除被CustomExcludeFilter判定为true的类。

使用useDefaultFilters属性:

@Configuration

@ComponentScan(basePackages = "com.example", useDefaultFilters = false)

public class AppConfig {

}

在这个例子中,Spring将只会扫描"com.example"包下标记了@Component注解的类,不会扫描其子包。

以上就是@ComponentScan的一些基本使用方法,在实际开发中可以根据需要选择合适的方法使用。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词