@Import注解作用
理解springboot自动装配时,发现@SpringBootApplication
注解下的@EnableAutoConfiguration
注解头上有一个@Import
注解。
关于这个注解的作用,上网查找后发现理解的不是很明白,于是写了下面的Demo去理解。
- 两个pojo类:
public class Person {
}
public class Student {
}
- 测试类
@Configuration
@Import({Student.class})
public class ImportConfig {
@Bean
public Person person(){
return new Person();
}
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ImportConfig.class,ApplicationTestConfig.class);
String[] names = context.getBeanDefinitionNames();
Student student = ApplicationTestConfig.getApplication(Student.class);
System.out.println("===="+student);
for (String name : names) {
System.out.println(name);
}
}
}
ApplicationTestConfig
类如下:
@Configuration
public class ApplicationTestConfig implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static <T> T getApplication(Class<T> clazz){
return applicationContext.getBean(clazz);
}
}
- 测试结果
====com.yjh.pojo.Student@649bec2e
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
importConfig
applicationTestConfig
com.yjh.pojo.Student
person
综上,其实@Import
注解的作用就是往当前类注入一个Bean,方便当前类的后续方法调用该Bean,跟Bean的作用差不多。
不过@Import
注解除了可以注入普通的Bean外,也可以注入实现了ImportSelector
接口和ImportBeanDefinitionRegistrar
接口的类。