How to use the @Import annotation in SpringBoot
May 31, 2023 pm 06:25 PM1. @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) // 通過(guò)@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了兩個(gè)哈 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 { /** * 用于指定需要注冊(cè)為bean的Class名稱 * 當(dāng)在@Configuration標(biāo)注的Class上使用@Import引入了一個(gè)ImportSelector實(shí)現(xiàn)類后,會(huì)把實(shí)現(xiàn)類中返回的Class名稱都定義為bean。 * * 通過(guò)其參數(shù)AnnotationMetadata importingClassMetadata可以獲取到@Import標(biāo)注的Class的各種信息, * 包括其Class名稱,實(shí)現(xiàn)的接口名稱、父類名稱、添加的其它注解等信息,通過(guò)這些額外的信息可以輔助我們選擇需要定義為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對(duì)應(yīng)的類,定義為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> * 通過(guò)其參數(shù)AnnotationMetadata importingClassMetadata可以獲取到@Import標(biāo)注的Class的各種信息, * 包括其Class名稱,實(shí)現(xiàn)的接口名稱、父類名稱、添加的其它注解等信息,通過(guò)這些額外的信息可以輔助我們選擇需要定義為Spring bean的Class名稱 */ @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { // 第一步:獲取到通過(guò)ComponentScan指定的包路徑 String[] basePackages = null; // @Import注解對(duì)應(yīng)的類上的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默認(rèn)為空數(shù)組 String basePackage = null; try { // @Import注解對(duì)應(yīng)的類的包名 basePackage = Class.forName(importingClassMetadata.getClassName()).getPackage().getName(); } catch (ClassNotFoundException e) { e.printStackTrace(); } basePackages = new String[]{basePackage}; } // 第er步,知道指定包路徑下所有實(shí)現(xiàn)了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,我們一般會(huì)實(shí)現(xiàn)ImportBeanDefinitionRegistrar類,然后配合一個(gè)自定義的注解一起使用。而且在注解類上@Import我們的這個(gè)實(shí)現(xiàn)類。 * 通過(guò)自定義注解的配置,拿到注解的一些元數(shù)據(jù)。然后在ImportBeanDefinitionRegistrar的實(shí)現(xiàn)類里面做相應(yīng)的邏輯處理,比如把自定義注解標(biāo)記的類添加到Spring IOC容器里面去。 */ public interface ImportBeanDefinitionRegistrar { /** * 根據(jù)注解的給定注釋元數(shù)據(jù),根據(jù)需要注冊(cè)bean定義 * @param importingClassMetadata 可以拿到@Import的這個(gè)class的Annotation Metadata * @param registry BeanDefinitionRegistry 就可以拿到目前所有注冊(cè)的BeanDefinition,然后可以對(duì)這些BeanDefinition進(jìn)行額外的修改或增強(qiáng)。 */ 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:
/** * 我們會(huì)把添加了該注解的類作為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

Undress AI Tool
Undress images for free

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

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

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)

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.

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

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

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

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

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. @Import introduces ordinary classes @Import introduces ordinary classes can help us 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, and @Repository all belong to @Component@SpringBootApplication@Import(ImportBean.class)//ImportBean through the @Import annotation
