在使用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. Spring之AOP简单demo

    1.加入JAR包.出了Spring自身的Jar包还要一些依赖的JAR包.不然会报ClassNotFound. Student.java package com.lubby.bean; import o ...

  2. zabbix3.0自动发现磁盘并监控磁盘IO

    Zabbix 版本:3.0 操作系统:Ubuntu16.04 操作环境,在被监控的主机上安装zabbix agent.安装方式为源码包安装. 简要安装步骤: 参考:https://www.zabbix ...

  3. Java 集合遍历

    在集合中使用Lambda表达式 Map集合中 forEach and Map 常规遍历-> 两种遍历: Map map = new HashMap(); map.put(102, "张 ...

  4. 阿里云搭建香港代理服务器 shadownsocks

    阿里云香港代理服务器搭建方式: 1.阿里云官网购买轻量级服务器即可,流量,配置套餐自己选择,CENTOS7,进入控制台后打开端口管理列表,打开9000即可. 2.安装shadownsocks服务端: ...

  5. Sass--调用混合宏

    在 Sass 中通过 @mixin 关键词声明了一个混合宏,那么在实际调用中,其匹配了一个关键词“@include”来调用声明好的混合宏.例如在你的样式中定义了一个圆角的混合宏“border-radi ...

  6. SQL回顾1

    1.学生表Student(SID,Sname,Sage,Ssex) --SID 学生编号,Sname 学生姓名,Sage 出生年月,Ssex 学生性别 2.课程表 Course(CID,Cname,T ...

  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. spring整合消息队列rabbitmq

    ps:本文只是简单一个整合介绍,属于抛砖引玉,具体实现还需大家深入研究哈.. 1.首先是生产者配置 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ...

  9. Flutter中的日期、格式化日期、日期选择器组件

    Flutter中的日期和时间戳 //獲取當前日期 DateTime _nowDate = DateTime.now(); print(_nowDate);//2019-10-29 10:57:20.3 ...

  10. Redis缓存在django中的配置

    django  settings中的配置 # 缓存 CACHES = { "default": { "BACKEND": "django_redis. ...