SpringBoot中的@Import注解四种使用方式详解

 更新时间:2023年12月29日 11:03:26   作者:my_sky_  
这篇文章主要介绍了SpringBoot中的@Import注解四种使用方式详解,@Import注解只可以标注在类上,可以结合 @Configuration注解、ImportSelector、ImportBeanDefinitionRegistrar一起使用,也可以导入普通的类,需要的朋友可以参考下

@Import注解四种使用方式

在介绍 @Import注解的使用之前,我们先看源码:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {
   /**
    * {@link Configuration @Configuration}, {@link ImportSelector},
    * {@link ImportBeanDefinitionRegistrar}, or regular component classes to import.
    */
   Class<?>[] value();
}

从注释来看,@Import注解只可以标注在类上,可以结合 @Configuration注解、ImportSelector、ImportBeanDefinitionRegistrar一起使用,也可以导入普通的类。

因此,@Import的使用方式有4种:直接导入类,导入配置类来导入Bean,导入 ImportSelector 的实现类,导入 ImportBeanDefinitionRegister 的实现类。

需要注意的是:ImportSelector、ImportBeanDefinitionRegistrar 这两个接口都必须依赖于 @Import 一起使用,而 @Import 可以单独使用。

我们熟悉的 @EnableAsync 、@EnableCaching、@EnableScheduling 等都是借助 @Import 注解来实现的。

需要导入的类

public class Hello {
	private String msg;
	
    public void print() {
    	if (msg != null) {
    		System.out.println(msg);
    	} else {
    		System.out.println("hello word");
    	}
    }
}

1、直接导入类

@Import(Hello.class)
public class SpringTestApplication {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringTestApplication.class);
        Hello hello = applicationContext.getBean(Hello.class);
        hello.print();
    }
}

项目中常用的方式如下:

@Import(Hello.class)
@Configuration
public class Config { 
}

2、导入配置类来导入Bean

@Configuration
public class HelloConfiguration {
    @Bean
    public Hello createHello() {
        return new Hello();
    }
}
@Import(HelloConfiguration.class)
public class SpringTestApplication {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringTestApplication.class);
        Hello hello = applicationContext.getBean(Hello.class);
        hello.print();
    }
}

这种方式使用较少,只要把配置类放到能被扫描到的包下,就可以去掉 @Import 导入。这种方式的使用场景是配置类无法被扫描到。

3、导入 ImportSelector 实现类

ImportSelector是一个接口,实现这个接口需要重写selectImports方法。selectImports方法会返回一个String数组,它包含的元素是需要被导入到容器中的类的全限定名。

下面我们实现 ImportSelector 接口并重写 selectImports 方法,将Hello类的全限定名返回。

public class HelloImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        List list = new ArrayList<>();
        list.add("a.b.domain.Hello");
        return StringUtils.toStringArray(list);
    }
}
@Import(HelloImportSelector.class)
public class SpringTestApplication {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringTestApplication.class);
        Hello hello = applicationContext.getBean(Hello.class);
        hello.print();
    }
}

上面是导入指定的类,ImportSelector 还可以实现根据条件导入某个类,例如 @EnableAsync 可以根据属性mode来选择实现代理的方式。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AsyncConfigurationSelector.class)
public @interface EnableAsync {
	Class<? extends Annotation> annotation() default Annotation.class;
	boolean proxyTargetClass() default false;
	AdviceMode mode() default AdviceMode.PROXY;
	int order() default Ordered.LOWEST_PRECEDENCE;
}
public class AsyncConfigurationSelector extends AdviceModeImportSelector {
	private static final String ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME =
			"org.springframework.scheduling.aspectj.AspectJAsyncConfiguration";
	@Override
	@Nullable
	public String[] selectImports(AdviceMode adviceMode) {
		switch (adviceMode) {
			case PROXY:
				return new String[] {ProxyAsyncConfiguration.class.getName()};
			case ASPECTJ:
				return new String[] {ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME};
			default:
				return null;
		}
	}
}
public abstract class AdviceModeImportSelector implements ImportSelector {
	...
}

像这种还不能决定注入哪个类,就可以实现此接口,根据条件或配置来注入合适的处理类。

4、导入 ImportBeanDefinitionRegistrar 实现类

当类实现了 ImportBeanDefinitionRegistrar 接口,就可以拿到注册器,可以向容器中注册任何的Bean,并且可以对Bean添加属性。

public class HelloImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Hello.class)
                .addPropertyValue("msg", "test")
                .getBeanDefinition();
        registry.registerBeanDefinition("hello", beanDefinition);
    }
}
@Import(HelloImportBeanDefinitionRegistrar.class)
public class SpringTestApplication {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringTestApplication.class);
        Hello hello = applicationContext.getBean(Hello.class);
        hello.print();
    }
}

到此这篇关于SpringBoot中的@Import注解四种使用方式详解的文章就介绍到这了,更多相关@Import注解四种使用方式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java DatabaseMetaData用法案例详解

    Java DatabaseMetaData用法案例详解

    这篇文章主要介绍了Java DatabaseMetaData用法案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • Springboot容器级后置处理器BeanDefinitionRegistryPostProcessor

    Springboot容器级后置处理器BeanDefinitionRegistryPostProcessor

    这篇文章主要介绍了Springboot容器级后置处理器BeanDefinitionRegistryPostProcessor,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2023-01-01
  • java中的 toString()方法实例代码

    java中的 toString()方法实例代码

    toString()方法 相信大家都用到过,一般用于以字符串的形式返回对象的相关数据。这篇文章主要介绍了java中的 toString()方法,需要的朋友可以参考下
    2017-05-05
  • 一文秒懂 kafka HA(高可用)

    一文秒懂 kafka HA(高可用)

    这篇文章主要介绍了秒懂 kafka HA(高可用)的相关知识,本文我们来说一说和 kafka 高可用相关的一些策略,对kafka HA相关知识感兴趣的朋友一起看看吧
    2021-11-11
  • Java通俗易懂系列设计模式之适配器模式

    Java通俗易懂系列设计模式之适配器模式

    这篇文章主要介绍了Java通俗易懂系列设计模式之适配器模式,对设计模式感兴趣的同学,一定要看一下
    2021-04-04
  • 深入浅析hbase的优点

    深入浅析hbase的优点

    本文讲述了HBase的特征和它的优点,并简要回顾了行键设计的重点之处,它还向你展示了如何在本地配置HBase环境,使用命令创建表、插入数据、检索指定行以及最后如何进行scan操作,感兴趣的朋友一起看看吧
    2017-09-09
  • 安装IDEA和配置Maven的步骤详解

    安装IDEA和配置Maven的步骤详解

    这篇文章主要介绍了安装IDEA和配置Maven的步骤详解,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-12-12
  • Springboot静态资源访问实现代码解析

    Springboot静态资源访问实现代码解析

    这篇文章主要介绍了Springboot静态资源访问实现代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • elasticsearch kibana简单查询讲解

    elasticsearch kibana简单查询讲解

    今天小编就为大家分享一篇关于elasticsearch kibana简单查询讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-02-02
  • 全面解析Java中的GC与幽灵引用

    全面解析Java中的GC与幽灵引用

    一般的应用程序不会涉及到 Reference 编程, 但是了解这些知识会对理解 GC 的工作原理以及性能调优有一定帮助,在实现一些基础性设施比如缓存时也可能会用到,希望本文能有所帮助
    2013-09-09

最新评论