bean的注入概述
在使用spring管理我们的bean的时候我们注入bean的方式有很多种,主要可以分为三大类
- 注解注入
- JavaConfig注入
- xml文件注入
ImportSelector
而且在这三大类注入方式里还会分为很多不同的注入方式,这里就不再赘述了,这里主要是介绍一种注解和JavaConfig一起使用的方式,通过ImportSelector接口、Import注解和自定义注解来实现bean的自动注入。
假如有如下的类需要注入到spring容器中
public class TestImportSelectorBean {
public void test(){
System.out.println("TestImportSelectorBean");
}
}
然后就需要一个实现了ImportSelector接口的实现类,那么就需要实现接口的方法,其中这个需要返回的string数组就是会自动注入的bean的名字,注意这里包含了包名
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{TestImportSelectorBean.class.getName()};
}
}
接下来就是将这个实现类注入到spring容器里,这里我们使用了两种方法
- 直接通过Import注入
@Configuration
@ComponentScan("com.zdd.spring")
@Import(MyImportSelector.class)
public class SpringConfig {
}
- 通过自定义注解注入
//这个注解会在运行时起作用
@Retention(RetentionPolicy.RUNTIME)
//注入ImportSelector的实现类
@Import(MyImportSelector.class)
public @interface MyAnnotation {
}
@Configuration
@ComponentScan("com.zdd.spring")
@MyAnnotation
public class SpringConfig {
}
最后是bean的调用,这里也可以用两种方法得到,通过实现类的class对象或者bean的名字。
需要注意的是bean的名字是包括包名的
//通过beanName获得bean,注意是全名,包括包名
TestImportSelectorBean bean = (TestImportSelectorBean) annotationConfigApplicationContext.getBean(TestImportSelectorBean.class.getName());
//通过实现类的class对象来获得bean
TestImportSelectorBean bean = annotationConfigApplicationContext.getBean(TestImportSelectorBean.class);