Three ways to use the @Import comment of the spring comment

Posted by m4x3vo on Sat, 04 Jan 2020 04:35:48 +0100

Catalog

@

1. @Import Notes

1. @Import can only be used on classes, @Import implements adding instances to spring's IOC container by means of fast import

 

2. There are many ways to add IOC containers, @Import annotations are relatively cowhide, @Import annotations can be used to import third-party packages, and of course @Bean annotations can be used, but @Import annotations are easier to quickly import

 


3. @Import annotation has three uses

2. @Import in three ways

The three main uses of @Import include:

1. Fill in the class array directly
2. ImportSelector Mode [Key]
3. ImportBeanDefinitionRegistrar method

2.1. First usage: Fill in the class array directly

Fill directly in the corresponding class array, which can be between 0 and more.

The syntax is as follows:

@Import({ Class name.class , Class name.class... })
public class TestDemo {

}

The beans for the corresponding import are added to the spring container, where the beans name is the full class name of the class, such as the com.yc.class name

2.2, Second usage: ImportSelector method [Key]

The premise of this approach is that a class implements the ImportSelector interface. If I use this method, the target object is the class Myclass, which is analyzed as follows:

Create Myclass class and implement ImportSelector interface

public class Myclass implements ImportSelector {
//Since it is the interface that must implement the method of this interface
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        return new String[0];
    }
}

Analyse the selectImports method that implements the interface:

  • 1. Return value: the full class name of the component we are actually importing into the container
  • 2. Parameters: AnnotationMetadata represents all the annotation information currently annotated by @Import [not the focus]

It is important to note that the selectImports method can return an empty array but cannot return null, otherwise a null pointer exception will be reported!

After the above analysis, the specific usage steps are as follows:

Step 1: Create a Myclass class and implement the ImportSelector interface, which is used to demonstrate adding a full class name to its return value

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

Step 2: Write the TestDemo class and label the Myclass class class using the ImportSelector style

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

}

As you can see, Yichun deliberately selected a dragon set character @Bean comment, which can be used as a reference for children's shoes whose @Bean comment is not very clear Spring's @bean comment in plain Chinese

Step 3: Write component test classes in print containers

/**
 * Component testing in print containers
 */
public class AnnotationTestDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(TestDemo.class);  //The parameters here represent the class to be operated on

        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String name : beanDefinitionNames){
            System.out.println(name);
        }

    }
}

Step 4: Run results

2.3, third usage: ImportBeanDefinitionRegistrar method

It's also an interface, similar to the second ImportSelector usage, with 80% similarity, but this usage compares custom registrations, as follows:

Step 1: Create the Myclass2 class and implement the ImportBeanDefinitionRegistrar interface

public class Myclass2 implements ImportBeanDefinitionRegistrar {
//The implementation defaults to null
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
      
    }
}

Parameter analysis:

  • First parameter: annotation Metadata, like the previous ImportSelector parameter, represents all the annotation information currently annotated by @Import
  • The second parameter represents the registration used to define a bean

Step 2: Write code to customize registered bean s

public class Myclass2 implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        //Specify the bean definition information (including the type, scope, etc.)
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(TestDemo4.class);
        //Register a bean Specify the bean name (id)
        beanDefinitionRegistry.registerBeanDefinition("TestDemo4444",rootBeanDefinition);
    }
}

Step 3: Write the TestDemo class and label the Myclass2 class using the ImportBeanDefinitionRegistrar style

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

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

}

Step 4: Run results

3. @Import Annotation Summary of Three Ways of Use

First usage: @Import ({component in container to import}): The container automatically registers this component, and the id defaults to the class name

 

Second usage: ImportSelector: Returns an array of the full class names of components that need to be imported, especially at the bottom of springboot

 

Third usage: ImportBeanDefinitionRegistrar: Manually register bean s to containers

All three of these usages can be mixed in one @Import, with special attention to the fact that the first and second are registered by full class names, and the third is customizable.

The @Import annotation itself is used a lot in springboot, especially the second way, ImportSelector, is used a lot in springboot, especially to master it!

If this article helps you a little, please give a compliment, thank you~

Finally, if there are any deficiencies or inaccuracies, you are welcome to correct the criticism and appreciate it!If in doubt, please leave a message and reply immediately!

Welcome to my Public Number, which contains some java learning materials and a large wave of Java e-books, such as Professor Zhou Zhiming's in-depth Java virtual machine, Java programming ideas, core technology volume, big story design mode, Java Concurrent Programming practice.....are all the Bibles of java, let's not say get on the Tomcat car, let's go!The most important thing is to explore technology together, yearn for technology, and pursue technology. Well, if you come, you'll be friends.

Topics: Java Spring SpringBoot Programming