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!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.