一.源码简要翻译
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.
* 导入一个或多个被Configuration注解的对象(导入到spring IOC容器中)
* <p>Provides functionality equivalent to the {@code <import/>} element in Spring XML.
* 等同于在spring 的xml文件中使用<import/>标签
* 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}).
* 允许导入被Configuration注解的类,ImportSelector和ImportBeanDefinitionRegistrar的实现类
* 以及在4.2开始的普通类。效果等同于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.
* 被导入的Configuration类中的@Bean声明的方法产生的bean,是可以被spring进行Autowired自动注入的。
* 无论是bean本身还是声明该bean的配置类实例都能进行自动注入。后一种方法显然更友好,更容易在IDE中
中进行查看
* <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.
* 如果xml或者其他非配置类声明的资源需要被导入,需要使用ImportResource注解来替代
* @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.
* 需要导入spring ioc 的配置类,IMportSelector,ImportBeanDefinitionRegistrar的实现类,或者
* 普通的组件类
*/
Class<?>[] value();
}
二.为什么要使用Import
springboot是有默认包扫描机制的,只有被spring扫描到的才会被实例化。默认是扫描启动类的当前包及其子包下的文件。那么引入其他jar包,并想被Spring管理,如何实现呢?
- 通过自动装配,自动装配类和其内部被@Bean注解的方法返回类都可以被实例化到spring容器里去。
- 但是有个问题,就是不可能所有想被spring管理的都放在一个类里吧。所以可以通过Import引入想要依赖的对象,并实例化到spring容器中去。
具体案例请参考 SpringCloud-Eureka服务端源码分析(4)(完善中)