在使用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. iviewUI框架,使用table表格内render下拉框select被遮盖问题

    使用props:{  transfer:true },即可   1.原本代码:

  2. Kaldi学习手记(一):Kaldi的编译安装

    下载 安装git sudo apt-get install git 下载Kaldi git clone https://github.com/kaldi-asr/kaldi.git kaldi-tru ...

  3. 廖雪峰Python电子书总结

    函数 1.注意:函数的默认参数必须指向不可变对象 未修改前: def add_end(L=[]): L.append('END') return L 存在的问题:如果连续调用多次,会出现多个 'END ...

  4. Python元类之由浅入深

    前言 ​ 元类属于python面向对象编程的深层次的魔法,非常重要,它使我们可以更好的掌控类从创建到消亡的整个生命周期过程.很多框架的源码中都使用到了元类.例如 Django Framework 中的 ...

  5. Djano中static和media文件路径的设置

    对于常用的css.js.image和常用的工具类在django项目中要设置一个全局的路径,对所有的app都可以访问到这个路径下的文件 1在django项目的setting文件中设置对应的static和 ...

  6. Sass--传一个不带值的参数

    Sass 的混合宏有一个强大的功能,可以传参,那么在 Sass 中传参主要有以下几种情形: A) 传一个不带值的参数 在混合宏中,可以传一个不带任何值的参数,比如: @mixin border-rad ...

  7. Linux系统常用知识(centos7)

    一.查看系统版本 1.查看linux内核版本 #cat /etc/redhat-release 二.主机名 2.1定义: 静态的(Static hostname):“静态”主机名也称为内核主机名,是系 ...

  8. 03.父工程pom、整合测试、SpringBootApplication注解

    父工程 idea点击spring-boot-starter-parent找到父工程spring-boot-dependencies模仿配置 父工程 <?xml version="1.0 ...

  9. cornerNet部分学习内容记录

    cornerNet来源灵感是基于多人姿态估计的从下往上思想,预测角的热图,根据嵌入式向量对角进行分组,其主干网络也来自于姿态估计的环面网络. cornerNet的总体框架结构图如下:  CornerN ...

  10. MySQL添加主键、索引

    查看索引  SHOW INDEX FROM  数据库表名 比如:SHOW INDEX FROM order_info; 添加索引 alter table 数据库add index 索引名称(数据库字段 ...