How to use the @Import annotation in SpringBoot
1. @Import introduces ordinary classes
By using the @Import annotation, we can define ordinary classes as Beans. @Import can be added to the classes corresponding to @SpringBootApplication (startup class), @Configuration (configuration class), and @Component (component class).
Note: @RestController, @Service, @Repository all belong to @Component
@SpringBootApplication @Import(ImportBean.class) // 通过@Import注解把ImportBean添加到IOC容器里面去 public class MyBatisApplication { public static void main(String[] args) { SpringApplication.run(MyBatisApplication.class, args); } }
2. @Import introduces the configuration class (@Configuration modification Class)
@Import In addition to defining ordinary classes as Bean, @Import can also introduce a class modified by @Configuration (introducing the configuration class), thereby making the configuration class take effect (all objects under the configuration class Bean is added to the IOC container). It is often used when customizing starters.
If the configuration class is under the standard SpringBoot package structure (the root directory of the SpringBootApplication startup class package). Spring Boot will automatically handle the import of configuration classes, and there is no need to manually use the @Import annotation. Typically, this situation applies when the @Configuration configuration class is outside the standard Spring Boot package structure. So it is generally used when customizing the starter.
@Configuration(proxyBeanMethods = false) @Import({ // import了两个哈 XXXDataConfiguration.XXXPartOneConfiguration.class, XXXDataConfiguration.XXXPartTwoConfiguration.class }) public class XXXDataAutoConfiguration { } public class XXXDataConfiguration { @Configuration(proxyBeanMethods = false) static class XXXPartOneConfiguration { @Bean @ConditionalOnMissingBean public BeanForIoc beanForIoc() { return new BeanForIoc(); } } @Configuration(proxyBeanMethods = false) static class XXXPartTwoConfiguration { /** * 省略了@Bean的使用 */ } }
3. @Import introduces the implementation class of ImportSelector
@Import can also introduce the implementation class of ImportSelector and define the Class names returned by the selectImports() method of the ImportSelector interface as beans . Pay attention to the parameter AnnotationMetadata of the selectImports() method. Through this parameter, we can obtain various information about the Class annotated with @Import. This is particularly useful for passing parameters. SpringBoot's automatic configuration and @EnableXXX annotations exist separately.
public interface ImportSelector { /** * 用于指定需要注册为bean的Class名称 * 当在@Configuration标注的Class上使用@Import引入了一个ImportSelector实现类后,会把实现类中返回的Class名称都定义为bean。 * * 通过其参数AnnotationMetadata importingClassMetadata可以获取到@Import标注的Class的各种信息, * 包括其Class名称,实现的接口名称、父类名称、添加的其它注解等信息,通过这些额外的信息可以辅助我们选择需要定义为Spring bean的Class名称 */ String[] selectImports(AnnotationMetadata importingClassMetadata); }
Regarding the use of the implementation class of ImportSelector introduced by @Import, we give a few simple usage scenarios (actual development is definitely more complicated than this).
3.1 Static import scenario (injecting known classes)
Static scenario (injecting known classes), it is very simple to directly return the class we need to define as a bean by implementing the ImportSelector class Okay, like the following example. Let's add an EnableXXX annotation and inject a known class XXX through XXXConfigurationSelector.
/** * XXXConfigurationSelector一定要配合@Import使用 */ public class XXXConfigurationSelector implements ImportSelector { @Override @NonNull public String[] selectImports(@NonNull AnnotationMetadata importingClassMetadata) { // 把XXX对应的类,定义为Bean return new String[]{XXX.class.getName()}; } } /** * 注意 @Import(XXXConfigurationSelector.class) */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(XXXConfigurationSelector.class) public @interface EnableXXX { } @SpringBootApplication @EnableXXX // 使之生效 public class MyBatisApplication { public static void main(String[] args) { SpringApplication.run(MyBatisApplication.class, args); } }
3.2 Dynamic import scenario (injecting classes with specified conditions)
To make such a function, we need to add all classes that implement the HelloService interface under the specified package path as beans to Go inside the IOC container. The @ComponentScan annotation is used to help us specify the path. The specific implementation is as follows:
public interface HelloService { void function(); } public class DynamicSelectImport implements ImportSelector { /** * DynamicSelectImport需要配合@Import()注解使用 * <p> * 通过其参数AnnotationMetadata importingClassMetadata可以获取到@Import标注的Class的各种信息, * 包括其Class名称,实现的接口名称、父类名称、添加的其它注解等信息,通过这些额外的信息可以辅助我们选择需要定义为Spring bean的Class名称 */ @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { // 第一步:获取到通过ComponentScan指定的包路径 String[] basePackages = null; // @Import注解对应的类上的ComponentScan注解 if (importingClassMetadata.hasAnnotation(ComponentScan.class.getName())) { Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(ComponentScan.class.getName()); basePackages = (String[]) annotationAttributes.get("basePackages"); } if (basePackages == null || basePackages.length == 0) { //ComponentScan的basePackages默认为空数组 String basePackage = null; try { // @Import注解对应的类的包名 basePackage = Class.forName(importingClassMetadata.getClassName()).getPackage().getName(); } catch (ClassNotFoundException e) { e.printStackTrace(); } basePackages = new String[]{basePackage}; } // 第er步,知道指定包路径下所有实现了HelloService接口的类(ClassPathScanningCandidateComponentProvider的使用) ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); TypeFilter helloServiceFilter = new AssignableTypeFilter(HelloService.class); scanner.addIncludeFilter(helloServiceFilter); Set<String> classes = new HashSet<>(); for (String basePackage : basePackages) { scanner.findCandidateComponents(basePackage).forEach(beanDefinition -> classes.add(beanDefinition.getBeanClassName())); } // 第三步,返回添加到IOC容器里面去 return classes.toArray(new String[0]); } } @Configuration @ComponentScan("com.tuacy.collect.mybatis") // 指定路径 @Import(DynamicSelectImport.class) public class DynamicSelectConfig { }
4. @Import introduces the implementation class of ImportBeanDefinitionRegistrar
@Import introduces the implementation class of ImportBeanDefinitionRegistrar. Generally used to dynamically register beans. The most important point is that you can alsomake additional modifications or enhancements to these BeanDefinitions. The mybatis @MapperScan we often use is implemented in this way.
/** * ImportBeanDefinitionRegistrar,我们一般会实现ImportBeanDefinitionRegistrar类,然后配合一个自定义的注解一起使用。而且在注解类上@Import我们的这个实现类。 * 通过自定义注解的配置,拿到注解的一些元数据。然后在ImportBeanDefinitionRegistrar的实现类里面做相应的逻辑处理,比如把自定义注解标记的类添加到Spring IOC容器里面去。 */ public interface ImportBeanDefinitionRegistrar { /** * 根据注解的给定注释元数据,根据需要注册bean定义 * @param importingClassMetadata 可以拿到@Import的这个class的Annotation Metadata * @param registry BeanDefinitionRegistry 就可以拿到目前所有注册的BeanDefinition,然后可以对这些BeanDefinition进行额外的修改或增强。 */ void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry); }
Regarding the use of ImportBeanDefinitionRegistrar introduced by @Import, it is strongly recommended that you take a look at mybatis's processing source code for @MapperScan. Very interesting. We also give a very simple example to let everyone intuitively see the use of ImportBeanDefinitionRegistrar. For example, we want to register all classes with BeanIoc annotations in the specified package path as beans.
The specific implementation is as follows:
/** * 我们会把添加了该注解的类作为bean */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented public @interface BeanIoc { } /** * 定义包路径。(指定包下所有添加了BeanIoc注解的类作为bean) * 注意这里 @Import(BeanIocScannerRegister.class) 的使用 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Import(BeanIocScannerRegister.class) public @interface BeanIocScan { String[] basePackages() default ""; } /** * 搜索指定包下所有添加了BeanIoc注解的类,并且把这些类添加到ioc容器里面去 */ public class BeanIocScannerRegister implements ImportBeanDefinitionRegistrar, ResourceLoaderAware { private final static String PACKAGE_NAME_KEY = "basePackages"; private ResourceLoader resourceLoader; @Override public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) { //1. 从BeanIocScan注解获取到我们要搜索的包路径 AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(BeanIocScan.class.getName())); if (annoAttrs == null || annoAttrs.isEmpty()) { return; } String[] basePackages = (String[]) annoAttrs.get(PACKAGE_NAME_KEY); // 2. 找到指定包路径下所有添加了BeanIoc注解的类,并且把这些类添加到IOC容器里面去 ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(beanDefinitionRegistry, false); scanner.setResourceLoader(resourceLoader); scanner.addIncludeFilter(new AnnotationTypeFilter(BeanIoc.class)); scanner.scan(basePackages); } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } } /** * 使用,使BeanIocScan生效 */ @Configuration @BeanIocScan(basePackages = "com.tuacy.collect.mybatis") public class BeanIocScanConfig { }
The above is the detailed content of How to use the @Import annotation in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

This article will write a detailed example to talk about the actual development of dubbo+nacos+Spring Boot. This article will not cover too much theoretical knowledge, but will write the simplest example to illustrate how dubbo can be integrated with nacos to quickly build a development environment.
