在使用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. 如何写一个简单的基于 Qt 框架的 HttpServer ?

    httpserver.h #ifndef HTTPSERVER_H #define HTTPSERVER_H #include <QObject> #include <QtCore& ...

  2. Visual Studio 插件ReSharper:代码生成工具

    下载地址:http://www.jetbrains.com/resharper/download/download-thanks.html?code=RSU&platform=windows ...

  3. Oracle安装client客户端报错Environment variable: "PATH"

    安装时出行这个错误 Environment variable: "PATH" 解决方法 1.找到你的安装包里的这个路径下的这两个文件 2.用文本方式打开 将里两个文件面所有的102 ...

  4. Python中集合类型的使用

    集合类型 多个不重复元素的无序组合 集合类型的表示 建立非空集合的方式可以用{}来表示 采用set()来表示 集合类型的操作符 S|T 返回一个新集合,这个集合包含S与T中的所有元素. S-T 返回一 ...

  5. vue,一路走来(5)--微信登录

    微信登录 今天又是周末了,想着博客还没记录完成.是的,下面记录一下微信登录遇到的问题. 在我的项目中,个人中心是需要完成授权登录才可以访问的,首先在定义路由的时候就需要多添加一个自定义字段requir ...

  6. 解决Minikube start卡住的方法

    安装与问题 在mac上安装minikube对k8s进行学习,根据官方Quick Start brew cask install minikube 就可以完成minikube的安装 在安装前需要安装vi ...

  7. spring boot 提纲

    http://tengj.top/categories/Spring-Boot%E5%B9%B2%E8%B4%A7%E7%B3%BB%E5%88%97/ http://blog.csdn.net/ca ...

  8. $Dsu$ $on$ $Tree$ 复习

    \(Dsu\) \(on\) \(Tree\) 复习 发现最近有点头晕,突然这东西就不会了,头疼了很久,决定写一份记录啊. 大致认识 适用范围一般在处理树上子树统计问题,不支持在线回答询问以及修改. ...

  9. Python中的"Special Method"

    The first thing to know about special methods is that they are meant to be called by the Python inte ...

  10. The Constructor with No Arguments

    If a class supplies at least one constructor but does not supply a no-argument constructor, it is il ...