Spring系列——@Import、ImportSelector接口
Spring注解之@Import
前言
大家使用的最多的给Spring注册组件的方式,大概是以下两种把。
- 包扫描+注解的方式(@Controller、@Service、@Reposity、@Comment)
- 使用@Configuration+@Bean的方式
这两种使用的区别:
- 第一种只能注册我们自己写的组件
- 而第二种可以注册第三方jar包里面的组件
接下来我来介绍第三种方式使用@Import来给Spring注册组件
@Import源码
/**
* Indicates one or more <em>component classes</em> to import — typically
* {@link Configuration @Configuration} classes.
*
* <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 ImportBeanDefinitionRegistrar
* @see ImportResource
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {
/**
* {@link Configuration @Configuration}, {@link ImportSelector},
* {@link ImportBeanDefinitionRegistrar}, or regular component classes to import.
*/
Class<?>[] value();
}
从源码中我们得知,这个注解是作用在类上面的并且注解能保留在运行期间。value属性的类型是Class
从注释中我们可以得知,@Import是为了提供与Xml配置中的import标签一样的功能,通过value属性注入组件,允许通过它引入 @Configuration 注解的类,引入ImportSelector接口,或者 ImportBeanDefinitionRegistrar进行注册组件。
@Improt实战
- Bean
package org.example.imports;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dog {
private String name;
}
- 配置类
package org.example.imports;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Import(