0%

注解Import

文章字数:216,阅读全文大约需要1分钟

将普通类导入到IOC容器中的注解

导入Bean的方法有

  1. @Bean注解
  2. @Controller @Service @Repository @Component等注解类,使用@ComponentScan扫描包
  3. @Import方法注入(4.2之前只能导入配置类)

常用方式

  • @Enablexxx注解中使用,此注解声明的类在加载之前会加载@inport注解中的类
  • 配合ImportSelector.class接口使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// BeanFactoryAware可以获取beanFactory相关信息
public class MyImportSelector implements ImportSelector, BeanFactoryAware {
private BeanFactory beanFactory;

@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}

@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
// importingClassMetadata可以获取注解所在类的其它注解信息
// 返回最终选择注入的className
return new String[]{XXXClass.class.getName()};
}
}
1
2
3
4
5
6
// 声明注解,并使用MyImportSelector
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(ElementType.TYPE)
@Import(MyImportSelector.class)
public @interface EnableXXX {}
1
2
3
// 在配置类上使用注解,就能在加载配置类之前加载好选择的类
@EnableXXX
@Configuration