我们知道springboot自动配置@EnableAutoConfiguration是通过@Import(AutoConfigurationImportSelector.class)来把自动配置组件加载进spring的context中的.
我们来看看@Import的定义:
/**
* 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.
翻译过来就是:
@Import用于声明引入一个或多个配置类,提供了等价于spring的XML配置中的<import/>元素的作用。
它允许引入带@Configuration的类,ImportSelector、ImportBeanDefinitionRegistrar的实现类,还有规则的组件类(AnnotationConfigApplicationContext类中通过register注册的注解,如@Componet、@Service等)。
在@Configuration的类中通过@Bean来声明的定义的类需要用@Autowired注入。不管是声明的配置类实例,还有配置类里面的bean,都能被自动注入。
后一种方法允许在@configuration类方法之间进行显式的、ide友好的导航。
@Import可以在类级别声明或作为元注释声明。
如果需要导入xml或其他非@configuration声明的bean定义,用importresource、importresource来代替之。
以下为自定义的自动配置代码:
1.声明一个自定义配置注解,@Import一个选择类。
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @Import(MyAutoConfigImportSelector.class) public @interface MyEnableAutoConfig { }
2. 引入配置的类:
public class MyAutoConfigImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[]{"org.zhanglang.test.config.custemAutoConfig.TestBean"}; } }
3.定义一个bean
public class TestBean { private int id = 100; public int getId() { return id; } }
4.测试主方法
@MyEnableAutoConfig public class MyApplication { public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(MyApplication.class);; TestBean testBean = context.getBean(TestBean.class); System.out.println(testBean.getId());//输出100 } }
ok..测试程序控制台输出了100。说明注入TestBean成功。完成自定义配置引入bean。