组件注册:@ComponentScan

@ComponentScan主要就是定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中。在配置类上添加 @ComponentScan 注解。该注解默认会扫描该类所在的包下所有的配置类,相当于之前的 <context:component-scan>。@ComponentScan注解默认装配标识了@Controller,@Service,@Repository,@Component注解的类到spring容器中。

例子:

在xml文件配置的方式,我们可以这样来进行配置:

在配置类里面写包扫描:

@Configuration
@ComponentScan(value="com.hlkj")
public class SpringConfig {
    @Bean
    public Person person() {
        return new Person("lisi",20);
    }
}

我们创建PersonController、PersonService、PersonDao这几个类,分别添加了@Controller@Service

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@ComponentScan.Filter是Spring框架中@ComponentScan注解的一部分,用于控制@ComponentScan扫描的bean的类型和名称。 @ComponentScan注解用于指示Spring应用程序扫描哪些包以查找组件类(例如,bean,配置类和其他带注释的类)。@ComponentScan.Filter可用于在扫描时排除或包含特定类型或名称的组件。 @ComponentScan.Filter支持四种类型的过滤器:按注释类型过滤,按正则表达式过滤,按指定类型过滤和按指定名称过滤。 以下是一些使用@ComponentScan.Filter的示例: 1. 按注释类型过滤: ```java @Configuration @ComponentScan(basePackages = "com.example", includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = MyAnnotation.class)) public class AppConfig { // configuration class code } ``` 这个例子中,Spring将仅扫描带有@MyAnnotation注释的组件。 2. 按正则表达式过滤: ```java @Configuration @ComponentScan(basePackages = "com.example", includeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = ".*Service")) public class AppConfig { // configuration class code } ``` 这个例子中,Spring将仅扫描名称以“Service”结尾的组件。 3. 按指定类型过滤: ```java @Configuration @ComponentScan(basePackages = "com.example", includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = MyService.class)) public class AppConfig { // configuration class code } ``` 这个例子中,Spring将仅扫描实现了MyService接口的组件。 4. 按指定名称过滤: ```java @Configuration @ComponentScan(basePackages = "com.example", includeFilters = @ComponentScan.Filter(type = FilterType.CUSTOM, value = MyComponentFilter.class)) public class AppConfig { // configuration class code } ``` 这个例子中,Spring将使用自定义MyComponentFilter类来决定哪些组件应该被包含在扫描中。 除了includeFilters之外,@ComponentScan还支持excludeFilters属性,用于指定哪些组件不应该被扫描
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值