在使用xml方式配置时,我们只需要在xml中配置如下代码:

<context:component-scan base-package="包名"></context:component-scan>

那么在java代码中使用如下四个注解,并且这些注解所在的包名是上面配置的包及其子包,那么spring会帮我们把相应的bean加如到IOC容器中。

  • @Controller

  • @Service
  • @Repository
  • @Component

在注解的方式下如何实现呢?在我们的配置类的上面加上如下注解即可

@ComponentScan(value={"包名1","包名2"})

此时该注解指定的几个包名及其子包中如果有类被上面四个注解修饰,那么就会自动被注入到IOC容器中。

注意:如果ComponentScan没有其它配置的化,默认扫描与其配置类相同的包。

1、实战


新建一个maven工程,添加如下依赖

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>

1、BookController

package com.yefengyu.annotation.controller;

import org.springframework.stereotype.Controller;

@Controller
public class BookController
{
}

2、BookService

package com.yefengyu.annotation.service;

import org.springframework.stereotype.Service;

@Service
public class BookService
{
}

3、BookRepository

package com.yefengyu.annotation.repository;

import org.springframework.stereotype.Repository;

@Repository
public class BookRepository
{
}

4、主配置类

package com.yefengyu.annotation.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @Configuration
@ComponentScan(value = "com.yefengyu.annotation")
public class MainConfig
{
}

5、测试

public static void main(String[] args)
{
ApplicationContext ctx= new AnnotationConfigApplicationContext(MainConfig.class);
String[] names = ctx.getBeanDefinitionNames();
for (String name : names)
{
System.out.println(name);
}
}

6、结果

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig
bookController
bookRepository
bookService

结果打印出如上内容,说明上面三个注解的bean都被添加到容器中。

2、规则过滤


@ComponentScan除了value 属性之外,还有其他属性,其中比较常用的是如下两个:

  • excludeFilters :排除哪些规则

  • includeFilters :指定哪些规则

他们的作用就是指定过滤规则。

1、指定规则

对于上面的代码,只需要修改主配置类中ComponentScan注解中的内容即可:

@ComponentScan(value = "com.yefengyu.annotation", includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Service.class)},useDefaultFilters = false)

上面的注解的含义是在com.yefengyu.annotation及其子包下面,将注解为Service的bean加入到容器中。注意useDefaultFilters 默认为true,表示使用默认的过滤规则:不过滤;如果需要指定规则,那么就需要将useDefaultFilters 设置为false。注意includeFilters 和useDefaultFilters 同时使用即可。

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig
bookService

2、排除规则

对于上面的代码,只需要修改主配置类中ComponentScan注解中的内容即可:

@ComponentScan(value = "com.yefengyu.annotation", excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Service.class)})

如果要排除某些规则,就要使用excludeFilters ,注意不需要使用useDefaultFilters ,默认即可。

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig
bookController
bookRepository

上面注解的含义就是在com.yefengyu.annotation及其子包下面,将注解为Controller的bean排除容器之外。

3、FilterType的类型

  • ANNOTATION:注解,常用

  • ASSIGNABLE_TYPE:给定类型,该类型及其子类、接口的实现类都起作用
  • ASPECTJ
  • REGEX:正则
  • CUSTOM:自定义

自定义类型的使用方式:

package com.yefengyu.annotation;

import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter; import java.io.IOException; public class MyTypeFilter implements TypeFilter
{
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
throws IOException
{
//获取当前类注解信息
AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
//获取当前扫描的类的信息
ClassMetadata classMetadata = metadataReader.getClassMetadata();
//获取当前扫描类资源信息
Resource resource = metadataReader.getResource(); String className = classMetadata.getClassName();
if (className.contains("er"))
{
return true;
}
return false;
}
}

实现TypeFilter接口,重写match方法,满足条件的则返回true.

然后指定扫描策略:

@ComponentScan(value = "com.yefengyu.annotation", excludeFilters = {@ComponentScan.Filter(type = FilterType.CUSTOM, classes = MyTypeFilter.class)})

结果如下:

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig
bookRepository

将类中含有er的排除在外。

4、指定多个ComponentScan

1、在jdk8以后可以直接写多个ComponentScan

@ComponentScan(basePackages = "com.yefengyu.annotation1")
@ComponentScan(basePackages = "com.yefengyu.annotation2")

2、也可以使用ComponentScans注解

@ComponentScans(value = {
@ComponentScan(basePackages = "com.yefengyu.annotation1"),
@ComponentScan(basePackages = "com.yefengyu.annotation2")
})

spring注解开发:ComponentScan组件扫描的更多相关文章

  1. Spring注解开发系列Ⅰ--- 组件注册(上)

    传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有两个缺点:1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分开.xml文件 ...

  2. 【Spring注解开发】组件注册-使用@Configuration和@Bean给容器中注册组件

    写在前面 在之前的Spring版本中,我们只能通过写XML配置文件来定义我们的Bean,XML配置不仅繁琐,而且很容易出错,稍有不慎就会导致编写的应用程序各种报错,排查半天,发现是XML文件配置不对! ...

  3. Spring注解开发系列Ⅱ --- 组件注册(下)

    1.@Import注册组件 @Import主要功能是通过导入的方式实现把实例加入springIOC容器中, /** * 给容器注册组件 * 1.包扫描+组件标注注解(@Controller,@Serv ...

  4. spring注解开发:容器中注册组件方式

    1.包扫描+组件标注注解 使用到的注解如下,主要针对自己写的类 @Controller @Service @Repository @Component @ComponentScan 参考 spring ...

  5. 浅尝Spring注解开发_自定义注册组件、属性赋值、自动装配

    Spring注解开发 浅尝Spring注解开发,基于Spring 4.3.12 包含自定义扫描组件.自定义导入组件.手动注册组件.自动注入方法和参数.使用Spring容器底层组件等 配置 @Confi ...

  6. 浅尝Spring注解开发_Bean生命周期及执行过程

    Spring注解开发 浅尝Spring注解开发,基于Spring 4.3.12 包含Bean生命周期.自定义初始化方法.Debug BeanPostProcessor执行过程及在Spring底层中的应 ...

  7. 浅尝Spring注解开发_Servlet3.0与SpringMVC

    浅尝Spring注解开发_Servlet 3.0 与 SpringMVC 浅尝Spring注解开发,基于Spring 4.3.12 Servlet3.0新增了注解支持.异步处理,可以省去web.xml ...

  8. Annotation(三)——Spring注解开发

    Spring框架的核心功能IoC(Inversion of Control),也就是通过Spring容器进行对象的管理,以及对象之间组合关系的映射.通常情况下我们会在xml配置文件中进行action, ...

  9. Spring IOC基础回顾 — 组件扫描和装配

    目录 注解形式配置应用IOC 1. 组件自动扫描 2. 组件依赖:为bean添加注解,实现自动注入 3. Spring IOC应用小结 注解形式配置应用IOC 在类定义.方法定义.成员变量定义前使用, ...

  10. Spring注解开发系列Ⅵ --- AOP&事务

    注解开发 --- AOP AOP称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等待,Struts2的拦截器设计就是基于AOP的思想,横向重复,纵向抽取.详细的AO ...

随机推荐

  1. 攻防世界--dmd-50

    测试文件:https://adworld.xctf.org.cn/media/task/attachments/7ef7678559ea46cbb535c0b6835f2f4d 1.准备 获取信息 6 ...

  2. Zookeeper3.4.14集群搭建

    环境: 3台centos7.4 1. 下载release:wget https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/zookeeper-3. ...

  3. 查看linux服务器的版本信息

    查看linux系统信息 uname -a Linux localhost.localdomain 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UT ...

  4. java访问ftp

    1.连接ftp FTPClient ftpClient = new FTPClient(); ftpClient.connect(host,port); ftpClient.login(userNam ...

  5. java23种设计模式(三)-- 适配器模式

    一.适配器模式 转载:https://www.cnblogs.com/V1haoge/p/6479118.html 适配器就是一种适配中间件,它存在于不匹配的二者之间,用于连接二者,将不匹配变得匹配, ...

  6. RPC_简洁版

    1.定义服务接口 public interface RpcService { int printHello(int msg); } 2.定义服务接口实现类 public class RpcInterf ...

  7. 苹果推出了AI手机,打造一款高度个性化的设备

    在今年苹果的WWDC 2018上,一些人认为今年会因为软件专注而缺乏新的MacBook和iPad而感到无聊,该公司宣布,iOS12的推出可能是迄今为止最重要的操作系统更新.一系列Siri增强功能,Ap ...

  8. springboot redis操作

    redis五大类型用法 Redis五大类型:字符串(String).哈希/散列/字典(Hash).列表(List).集合(Set).有序集合(sorted set)五种Controller:@Reso ...

  9. IO流 读写文件

    读写文件 如前所述,一个流被定义为一个数据序列.输入流用于从源读取数据,输出流用于向目标写数据. 下图是一个描述输入流和输出流的类层次图. 下面将要讨论的两个重要的流是 FileInputStream ...

  10. CPU缓存

    原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11520840.html 由于CPU发展的速度远快于内存的发展,CPU的处理速度就比内存的访问速度快得多 ...