一、使用@Import注解导入组件

@Import注解的作用是给容器中导入组件,回顾下我们给容器中导入组件的方式,可以通过Spring的xm配置方式,可以通过注解,如@Component等,也可以通过java配置类的方式给容器中导入注解,今天来介绍另一个注解,其作用也是给容器中导入组件。


其用法非常简单,我们举个小例子 ,

配置类MainConfig2

@Configuration
@Import({Color.class,Red.class})//将这两个类导入到容器中
//@Import导入组件,id默认是组件的全类名
public class MainConfig2 { }

其中Color.class和Red.class就是两个非常普通的java类,不必关心这两个类有何特殊的。

我们写个测试方法,用于遍历下容器中bean组件的名字

@Test
public void printBeans(AnnotationConfigApplicationContext applicationContext){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
String[] definitionNames = applicationContext.getBeanDefinitionNames();
for (String name : definitionNames) {
System.out.println(name);
}
}

我们关注下打印的结果:

mainConfig2
com.atguigu.bean.Color //@Import导入组件,id默认是组件的全类名
com.atguigu.bean.Red

二、@Import导入ImportSelector

上面可以看到 ,这种方式进行导入呢?还是略微麻烦了点,如果组件很多,也是比较麻烦的,所以呢,我们也可以结合ImportSelector来使用

首先,我们再写两个类,叫做Bule.java和Yellow.java,不必关心类里有什么,哪怕是个空类也是可以的,我们只关心其是否能被正确注入到组件之中

那如何使用ImportSelector呢?

这是一个接口,继承并实现即可。

//自定义逻辑返回需要导入的组件
public class MyImportSelector implements ImportSelector { //返回值,就是到导入到容器中的组件全类名
//AnnotationMetadata:当前标注@Import注解的类的所有注解信息
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
//方法不要返回null值
return new String[]{"com.atguigu.bean.Blue","com.atguigu.bean.Yellow"};
}
}

关于这个导入选择器,从这个方法名selectImports就可以看出,,是选择性的导入的意思,所以在这个方法中,我们是可以通过编写不同的逻辑,来返回我们需要导入的组件,那上面自定义的选择导入器,只是为了演示,所以没有具体的条件判断等,可自行扩展,返回需要导入的组件Blue和Yellow

,然后将这个类加入到@Import注解的参数中,就像这样

@Configuration
@Import({Color.class,Red.class,MyImportSelector.class})//将这两个类导入到容器中
//@Import导入组件,id默认是组件的全类名
public class MainConfig2 {
}

我们还是用刚才的测试方法打印下结果:

mainConfig2
com.atguigu.bean.Color
com.atguigu.bean.Red
com.atguigu.bean.Blue //Blue被注册进了容器中
com.atguigu.bean.Yellow // Yellow被注册进了容器中

以上就是ImportSelector接口的使用,是比较简单的。

三、@Import导入ImportBeanDefinitionRegistrar

ImportBeanDefinitionRegistrar与ImportSelector的使用大致相同,它是接口,我们只需实现它,并将它作为参数,放在@Import中即可,。

自定义实现类MyImportBeanDefinitionRegistrar

public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

	/**
* AnnotationMetadata:当前类的注解信息
* BeanDefinitionRegistry:BeanDefinition注册类;
* 把所有需要添加到容器中的bean;调用
* BeanDefinitionRegistry.registerBeanDefinition手工注册进来
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { boolean definition = registry.containsBeanDefinition("com.atguigu.bean.Red");
boolean definition2 = registry.containsBeanDefinition("com.atguigu.bean.Blue");
if(definition && definition2){
//指定Bean定义信息;(Bean的类型,Bean。。。)
RootBeanDefinition beanDefinition = new RootBeanDefinition(RainBow.class);
//注册一个Bean,指定bean名
registry.registerBeanDefinition("rainBow", beanDefinition);
}
} }

在配置类的@Import注解中加入这个自定义的类

@Configuration
@Import({Color.class,Red.class,MyImportSelector.class,MyImportBeanDefinitionRegistrar.class})//将这两个类导入到容器中
//@Import导入组件,id默认是组件的全类名
public class MainConfig2 {
}

依旧使用刚才的测试方法打印一下

mainConfig2
com.atguigu.bean.Color
com.atguigu.bean.Red
com.atguigu.bean.Blue
com.atguigu.bean.Yellow
rainBow // 自定义MyImportBeanDefinitionRegistrar的注册组件

对比后两种注册方法,我们发现,ImportBeanDefinitionRegistrar是没有返回值的,另外它多了一个参数BeanDefinitionRegistry,也就是可以直接在方法中就注册bean。

四、详细分析

我们来看下ImportBeanDefinitionRegistrar的源码,

package org.springframework.context.annotation;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.core.type.AnnotationMetadata;
public interface ImportBeanDefinitionRegistrar {
/**
* Register bean definitions as necessary based on the given annotation metadata of
* the importing {@code @Configuration} class.
* <p>Note that {@link BeanDefinitionRegistryPostProcessor} types may <em>not</em> be
* registered here, due to lifecycle constraints related to {@code @Configuration}
* class processing.
* @param importingClassMetadata annotation metadata of the importing class
* @param registry current bean definition registry
*/
public void registerBeanDefinitions(
AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry); }

我们看下方法第一个参数AnnotationMetadata importingClassMetadata,这个是注解的元信息,即配置类上所有注解的信息,然后可以在MyImportBeanDefinitionRegistrar自定义我们自己需要的逻辑,动态注册bean、

不同的是,这个类通过BeanDefinitionRegistry本身就可以注册组件。

五、Spring中的@Import注解的更多相关文章

  1. spring 中的@Import注解和@ImportResource注解

    概述:@Import注解是引入带有@Configuration的java类. @ImportResource是引入spring配置文件.xml 案例的核心代码如下: package com.timo. ...

  2. spring框架中的@Import注解

    spring框架中的@Import注解 Spring框架中的@Import注解 在之前的文章中,作者介绍了Spring JavaConfig. 这是除了使用传统的XML文件之外,spring带来的新的 ...

  3. 第5章—构建Spring Web应用程序—关于spring中的validate注解后台校验的解析

    关于spring中的validate注解后台校验的解析 在后台开发过程中,对参数的校验成为开发环境不可缺少的一个环节.比如参数不能为null,email那么必须符合email的格式,如果手动进行if判 ...

  4. Spring 中aop切面注解实现

    spring中aop的注解实现方式简单实例   上篇中我们讲到spring的xml实现,这里我们讲讲使用注解如何实现aop呢.前面已经讲过aop的简单理解了,这里就不在赘述了. 注解方式实现aop我们 ...

  5. Spring中的常用注解

    Spring中的常用注解 1.@Controller 标识一个该类是Spring MVC controller处理器,用来创建处理http请求的对象.

  6. Spring中重要的注解

    现在大部分的Spring项目都会用到注解.使用注解来替换xml,一行简单的注解就可以解决很多事情.但是你真的懂其中的原理吗. 本文翻译于 https://docs.spring.io/spring-f ...

  7. JavaEE开发之Spring中的条件注解组合注解与元注解

    上篇博客我们详细的聊了<JavaEE开发之Spring中的多线程编程以及任务定时器详解>,本篇博客我们就来聊聊条件注解@Conditional以及组合条件.条件注解说简单点就是根据特定的条 ...

  8. spring中aop的注解实现方式简单实例

    上篇中我们讲到spring的xml实现,这里我们讲讲使用注解如何实现aop呢.前面已经讲过aop的简单理解了,这里就不在赘述了. 注解方式实现aop我们主要分为如下几个步骤(自己整理的,有更好的方法的 ...

  9. JavaEE开发之Spring中的条件注解、组合注解与元注解

    上篇博客我们详细的聊了<JavaEE开发之Spring中的多线程编程以及任务定时器详解>,本篇博客我们就来聊聊条件注解@Conditional以及组合条件.条件注解说简单点就是根据特定的条 ...

随机推荐

  1. Longest Common Substring II SPOJ - LCS2 (后缀自动机)

    Longest Common Substring II \[ Time Limit: 236ms\quad Memory Limit: 1572864 kB \] 题意 给出\(n\)个子串,要求这\ ...

  2. [RN] React Native 仿美团下拉筛选菜单控件

    React Native 仿美团下拉筛选菜单控件 演示效果如下: 使用方法如下: 1.安装 npm install react-native-dropdownmenus --save react-na ...

  3. 洛谷P4735题解

    若想要深入学习可持久化0-1Trie树,传送门. Description: 给定数列 \(\{a_n\}\) ,支持两种操作: 在数列尾添加一个数 \(x\) ,数列长度变成 \(n+1\) ; 给定 ...

  4. nginx 访问控制之 限速

    nginx限速可以通过 ngx_http_limit_conn_module 和 ngx_http_limit_req_module 模块来实现限速的功能. 一.ngx_http_limit_conn ...

  5. Dice Similarity Coefficent vs. IoU Dice系数和IoU

    Dice Similarity Coefficent vs. IoU Several readers emailed regarding the segmentation performance of ...

  6. qt5 qmake开发

    mkdir hello helloworld.cpp #include <QPushButton> #include <QApplication> int main(int a ...

  7. An intriguing failing of convolutional neural networks and the CoordConv solution

    An intriguing failing of convolutional neural networks and the CoordConv solution NeurIPS 2018 2019- ...

  8. jquery ajax Uncaught TypeError :Illegal invocation 报错

    使用jquery ajax异步提交的时候报Uncaught TypeError :Illegal invocation错误,报错如图: 基本上,导致这个错误的原因一般有以下两点: 1.请求类型有误,如 ...

  9. 关于“javax.servlet.include.request_uri”属性值 include 请求 RequestDispatcher.include

    在springMVC的DispatcherServlet类的doService方法中有如下代码: 1 2 3 4 5 6 7 8 9 10 if (WebUtils.isIncludeRequest( ...

  10. nodejs相关框架

    sails   https://sailsjs.com/documentation/concepts koa  koa 是由 Express 原班人马打造的,致力于成为一个更小.更富有表现力.更健壮的 ...