Three different ways @Import annotated notes of spring spring @Import annotation of notes used in three ways

Excerpt: https://www.cnblogs.com/yichunguo/p/12122598.html

@Import annotated notes of spring used in three ways

 

@

1, @ Import notes Notes

. 1, @Import only with class  , @ Import achieved by way of examples of the rapid introduction of the spring IOC vessel was added

 

 

2, to join the IOC container are many ways, @ Import notes the relatively very leather, @Import annotation can be used to import third-party packages  , of course @Bean annotation can be, but the way @Import notes quickly import more convenient

 


3, @ Import notes there are three usage

 

2, @ Import of three uses

Three uses @Import include:

1, direct way to fill an array of class
2, ImportSelector way [focus]
3, ImportBeanDefinitionRegistrar way

2.1, the first usage: directly fill an array of class

Direct filling array corresponding class, class 0 can have a plurality of arrays.

The syntax is as follows:

@Import({ 类名.class , 类名.class... })
public class TestDemo {

}

Corresponding import are to be added to the spring bean container, the bean class names in the container is in the full class name  , class name such com.yc.

2.2, the second usage: ImportSelector way [emphasis]

The premise of this approach is that a class to implement the interface ImportSelector, if I want to use this method, the target object is Myclass this class analysis as follows:

Creating Myclass class and implement the interface ImportSelector

public class Myclass implements ImportSelector { //既然是接口肯定要实现这个接口的方法 @Override public String[] selectImports(AnnotationMetadata annotationMetadata) { return new String[0]; } }

Analysis selectImports interface method implementation of:

  • 1, the return value: what we actually want to import components into a container full class name [ focus  ]
  • 2, parameter: AnnotationMetadata represents the currently @Import annotated notes to label all the information is not the point []

Note that selectImports method returns an empty array but can not return null, otherwise it will be reported null pointer exception!

After completion of the above analysis, the specific use of the following steps:

Step 1: Create Myclass class and implement ImportSelector interface is used here to demonstrate a full class name is added to the return value

public class Myclass implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata annotationMetadata) { return new String[]{"com.yc.Test.TestDemo3"}; } }

Step Two: Write TestDemo class, and marked the way of using ImportSelector Myclass class

@Import({TestDemo2.class,Myclass.class})
public class TestDemo {
        @Bean
        public AccountDao2 accountDao2(){
            return new AccountDao2(); } }

As can be seen, Yichun deliberately picked a cameo role @Bean notes, if notes are not very clear on @Bean shoes can refer to the vernacular to explain the Spring of @bean comment

The third step: preparation of test printing component class container

/**
 * 打印容器中的组件测试
 */
public class AnnotationTestDemo {
    public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(TestDemo.class); //这里的参数代表要做操作的类 String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); for (String name : beanDefinitionNames){ System.out.println(name); } } }

Step Four: Run results
Here Insert Picture Description

2.3, the third usage: ImportBeanDefinitionRegistrar way

It is also an interface similar to the second ImportSelector usage, 80% similarity, but this usage is relatively Custom Registration, as follows:

Step 1: Create Myclass2 class and implement the interface ImportBeanDefinitionRegistrar

public class Myclass2 implements ImportBeanDefinitionRegistrar { //该实现方法默认为空 @Override public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) { } }

Parametric analysis:

  • The first argument: annotationMetadata and parameters are the same as before ImportSelector information indicates that all notes currently @Import to comment marked
  • The second parameter indicates a register defines a bean

Step two: writing code, custom registration bean

public class Myclass2 implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) { //指定bean定义信息(包括bean的类型、作用域...) RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(TestDemo4.class); //注册一个bean指定bean名字(id) beanDefinitionRegistry.registerBeanDefinition("TestDemo4444",rootBeanDefinition); } }

Step Three: Write TestDemo class, and marked on the use ImportBeanDefinitionRegistrar way Myclass2 class

@Import({TestDemo2.class,Myclass.class,Myclass2.class})
public class TestDemo {

        @Bean
        public AccountDao2 accountDao222(){
            return new AccountDao2(); } }

Step Four: Run results
Here Insert Picture Description

3, three different ways @ Import annotated summary

The first use of: @Import(a container to be imported {components}): the component container is automatically registered, ID is fully qualified class name of the default

 

第二种用法:ImportSelector:返回需要导入的组件的全类名数组,springboot底层用的特别多【重点 

 

 

 

第三种用法:ImportBeanDefinitionRegistrar:手动注册bean到容器

以上三种用法方式皆可混合在一个@Import中使用,特别注意第一种和第二种都是以全类名的方式注册,而第三中可自定义方式。

@Import注解本身在springboot中用的很多,特别是其中的第二种用法ImportSelector方式在springboot中使用的特别多,尤其要掌握!

如果本文对你有一点点帮助,那么请点个赞呗,谢谢~

最后,若有不足或者不正之处,欢迎指正批评,感激不尽!如果有疑问欢迎留言,绝对第一时间回复!

欢迎各位关注我的公众号,里面有一些java学习资料和一大波java电子书籍,比如说周志明老师的深入java虚拟机、java编程思想、核心技术卷、大话设计模式、java并发编程实战.....都是java的圣经,不说了快上Tomcat车,咋们走!最主要的是一起探讨技术,向往技术,追求技术,说好了来了就是盆友喔...

Here Insert Picture Description

不曾飞舞的每一天都是对生命的一种辜负....
 
分类:  Spring学习专栏

@

1、@Import注解须知

1、@Import只能用在类上 ,@Import通过快速导入的方式实现把实例加入spring的IOC容器中

 

 

2、加入IOC容器的方式有很多种,@Import注解就相对很牛皮了,@Import注解可以用于导入第三方包 ,当然@Bean注解也可以,但是@Import注解快速导入的方式更加便捷

 


3、@Import注解有三种用法

 

2、@Import的三种用法

@Import的三种用法主要包括:

1、直接填class数组方式
2、ImportSelector方式【重点】
3、ImportBeanDefinitionRegistrar方式

2.1、第一种用法:直接填class数组

直接填对应的class数组,class数组可以有0到多个。

语法如下:

@Import({ 类名.class , 类名.class... })
public class TestDemo {

}

对应的import的bean都将加入到spring容器中,这些在容器中bean名称是该类的全类名 ,比如com.yc.类名

2.2、第二种用法:ImportSelector方式【重点】

这种方式的前提就是一个类要实现ImportSelector接口,假如我要用这种方法,目标对象是Myclass这个类,分析具体如下:

创建Myclass类并实现ImportSelector接口

public class Myclass implements ImportSelector { //既然是接口肯定要实现这个接口的方法 @Override public String[] selectImports(AnnotationMetadata annotationMetadata) { return new String[0]; } }

分析实现接口的selectImports方法中的:

  • 1、返回值: 就是我们实际上要导入到容器中的组件全类名【重点 
  • 2、参数: AnnotationMetadata表示当前被@Import注解给标注的所有注解信息【不是重点】

需要注意的是selectImports方法可以返回空数组但是不能返回null,否则会报空指针异常!

以上分析完毕之后,具体用法步骤如下:

第一步:创建Myclass类并实现ImportSelector接口,这里用于演示就添加一个全类名给其返回值

public class Myclass implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata annotationMetadata) { return new String[]{"com.yc.Test.TestDemo3"}; } }

第二步:编写TestDemo 类,并标注上使用ImportSelector方式的Myclass类

@Import({TestDemo2.class,Myclass.class})
public class TestDemo {
        @Bean
        public AccountDao2 accountDao2(){
            return new AccountDao2(); } }

可以看出,宜春故意挑了个龙套角色@Bean注解,若对@Bean注解不是很清晰的童鞋可以参考大白话讲解Spring的@bean注解

第三步:编写打印容器中的组件测试类

/**
 * 打印容器中的组件测试
 */
public class AnnotationTestDemo {
    public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(TestDemo.class); //这里的参数代表要做操作的类 String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); for (String name : beanDefinitionNames){ System.out.println(name); } } }

第四步:运行结果
Here Insert Picture Description

2.3、第三种用法:ImportBeanDefinitionRegistrar方式

同样是一个接口,类似于第二种ImportSelector用法,相似度80%,只不过这种用法比较自定义化注册,具体如下:

第一步:创建Myclass2类并实现ImportBeanDefinitionRegistrar接口

public class Myclass2 implements ImportBeanDefinitionRegistrar { //该实现方法默认为空 @Override public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) { } }

参数分析:

  • 第一个参数:annotationMetadata 和之前的ImportSelector参数一样都是表示当前被@Import注解给标注的所有注解信息
  • 第二个参数表示用于注册定义一个bean

第二步:编写代码,自定义注册bean

public class Myclass2 implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) { //指定bean定义信息(包括bean的类型、作用域...) RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(TestDemo4.class); //注册一个bean指定bean名字(id) beanDefinitionRegistry.registerBeanDefinition("TestDemo4444",rootBeanDefinition); } }

第三步:编写TestDemo 类,并标注上使用ImportBeanDefinitionRegistrar方式的Myclass2类

@Import({TestDemo2.class,Myclass.class,Myclass2.class})
public class TestDemo {

        @Bean
        public AccountDao2 accountDao222(){
            return new AccountDao2(); } }

第四步:运行结果
Here Insert Picture Description

3、@Import注解的三种使用方式总结

第一种用法:@Import({ 要导入的容器中的组件 } ):容器会自动注册这个组件,id默认是全类名

 

第二种用法:ImportSelector:返回需要导入的组件的全类名数组,springboot底层用的特别多【重点 

 

 

 

第三种用法:ImportBeanDefinitionRegistrar:手动注册bean到容器

以上三种用法方式皆可混合在一个@Import中使用,特别注意第一种和第二种都是以全类名的方式注册,而第三中可自定义方式。

@Import注解本身在springboot中用的很多,特别是其中的第二种用法ImportSelector方式在springboot中使用的特别多,尤其要掌握!

如果本文对你有一点点帮助,那么请点个赞呗,谢谢~

最后,若有不足或者不正之处,欢迎指正批评,感激不尽!如果有疑问欢迎留言,绝对第一时间回复!

I welcome you to focus on the public number, there are some java learning materials and a large wave of java e-books, such as Zhou Zhiming teacher depth java virtual machine, java programming ideas, the core technology volume, Westward design patterns, java concurrent programming combat ... .. is a java Bible, do not say fast car on Tomcat, ye who go! The main thing is to explore technology, yearning technology, the pursuit of technology, said good pots Friends is coming Oh ...

Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/xichji/p/12147926.html