最近在看spring5.1以及mybatis-spring源码的时候,发现@MapperScan以及很多springboot的@EnableXXX注解,都用到了这个@Import注解。所以打算仔细研究下该注解的作用。
顺便把类似的@ImportRescource也在这里总结一下。
一、@Import简介
简介:在Spring3.0之前,我们的bean可以通过xml配置文件和扫描特定包下的类来将指定的bean注入到Spring容器中。Spring 3.0之后提供了JavaConfig的方式,也就是将Spring容器里bean的元信息以java代码的方式进行描述。即通过@Configuration与@Bean这两个注解配合使用来将原来配置在xml文件里的Bean通过java代码的方式进行描述,进而将bean注入到Spring容器中。
根据下面的源码,我们可以简单的总结,主要有三种用法:
- 功能类似XML配置的,用来导入配置类。
- 可以导入带有@Configuration注解的配置类或实现了ImportSelector或portBeanDefinitionRegistrar。
- 导入普通的POJO(Spring会将其注册成Spring Bean,导入POJO需要使用Spring 4.2以上)。
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Indicates one or more {@link Configuration @Configuration} classes to import.
*
* <p>Provides functionality equivalent to the {@code <import/>} element in Spring XML.
* Allows for importing {@code @Configuration} classes, {@link ImportSelector} and
* {@link ImportBeanDefinitionRegistrar} implementations, as well as regular component
* classes (as of 4.2; analogous to {@link AnnotationConfigApplicationContext#register}).
*
* <p>{@code @Bean} definitions declared in imported {@code @Configuration} classes should be
* accessed by using {@link org.springframework.beans.factory.annotation.Autowired @Autowired}
* injection. Either the bean itself can be autowired, or the configuration class instance
* declaring the bean can be autowired. The latter approach allows for explicit, IDE-friendly
* navigation between {@code @Configuration} class methods.
*
* <p>May be declared at the class level or as a meta-annotation.
*
* <p>If XML or other non-{@code @Configuration} bean definition resources need to be
* imported, use the {@link ImportResource @ImportResource} annotation instead.
*
* @author Chris Beams
* @author Juergen Hoeller
* @since 3.0
* @see Configuration
* @see ImportSelector
* @see ImportResource
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {
/**
* {@link Configuration}, {@link ImportSelector}, {@link ImportBeanDefinitionRegistrar}
* or regular component classes to import.
*/
Class<?>[] value();
}
二、@Import用法详解
1、ImportSelector
- 根据AnnotationMetadata(实质上是引入标注了@Import注解的类的注解信息),来判断是否引入哪些配置类,通过字符串数组的方式返回配置类的全限定名。
2、DeferredImportSelector
- ImportSelector的子接口,区别是,他会在所有的@Configuration类加载完成之后再加载返回的配置类。ImportSelector会在当前Configuration类加载之前去加载返回的配置类。
- 可以使用@Order注解或者Ordered接口来指定DeferredImportSelector的加载顺序。
- 并且提供了新的方法getImportGroup()用来跨DeferredImportSelector实现自定义Configuration的加载顺序。
3、ImportBeanDefinitionRegistrar
- 根据AnnotationMetadata(实质上是引入标注了@Import注解的类的注解信息), 来注册BeanDenfinition,通过BeanDefinitionRegistry实例的register可以注册BeanDefinition。
三、@Import代码测试
package com.evan.config;
import com.evan.service.JustinService;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({MyImportSelector.class,MyImportBeanDefinitionRegistrar.class,OtherConfig.class, JustinService.class})
public class MyConfig {
}
package com.evan.config;
import com.evan.service.TomService;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
//使用ImportBeanDefinitionRegistrar的方式,直接导入BeanDefinition
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
registry.registerBeanDefinition("TomService", new RootBeanDefinition(TomService.class));
}
}
package com.evan.config;
import com.evan.service.EvanService;
import com.evan.service.PersonService;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
//使用ImportSelector导入,相当于@Bean
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
//返回String数组。
return new String[]{EvanService.class.getName(), PersonService.class.getName()};
}
}
package com.evan.config;
import com.evan.service.JayService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//直接导入配置类
@Configuration
public class OtherConfig {
@Bean
public JayService jay(){
return new JayService();
}
}
package com.evan.service;
public class EvanService {
}
package com.evan.service;
public class JayService {
}
package com.evan.service;
public class JustinService {
}
package com.evan.service;
public class PersonService {
}
package com.evan.service;
public class TomService {
}
主测试类:
package com.evan.test;
import com.evan.config.MyConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
ac.register(MyConfig.class);
ac.refresh();
String[] beanDefinitionNames = ac.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
System.out.println(beanDefinitionName);
}
}
}
运行结果:
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
myConfig
com.evan.service.EvanService
com.evan.service.PersonService
com.evan.config.OtherConfig
jay
com.evan.service.JustinService
TomService