@import注解的主要作用是将类注入到spring的上下文中去
用法1在加了@Configuration注解的配置类中使用
- //配置类,将被其他配置类引用
- @Configuration
- public class MybatisConfig {
- }
- //引用MybatisConfig配置类
- @Configuration
- @Import(value = {MybatisConfig.class})
- public class JavaConfig {
-
- public static void main(String[] args) {
- ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class);
- for (String str :ac.getBeanDefinitionNames()) {
- System.out.println(str);
- }
- }
- }
运行结果
javaConfig
com.test.config.MybatisConfig
用法2实现ImportSelector接口的类
- //实现ImportSelector接口,并可以加条件判断是否要注入spring
- public class Test implements ImportSelector {
- @Override
- public String[] selectImports(AnnotationMetadata annotationMetadata) {
- String[] strings = new String[1];
- if (1==1){
- strings[0] = Ab.class.getName();
- }
- return strings;
- }
- }
- //将上边的Test类加入
- @Configuration
- @Import(value = {MybatisConfig.class,Test.class})
- public class JavaConfig {
-
- public static void main(String[] args) {
- ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class);
- for (String str :ac.getBeanDefinitionNames()) {
- System.out.println(str);
- }
- }
- }
观察结果,Ab类也注入了spring环境中
javaConfig
com.test.config.MybatisConfig
com.test.config.Ab
用法3实现 ImportBeanDefinitionRegistrar接口,自己定义beanDefininition
- //实现ImportBeanDefinitionRegistrar,在BeanDefinitionRegistry中加入BeanDefinition
- public class Test1 implements ImportBeanDefinitionRegistrar {
- @Override
- public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
- // 注册dog的bean定义,其中beanName为dogBean
- RootBeanDefinition rbd = new RootBeanDefinition(Ab.class);
- registry.registerBeanDefinition("ab",rbd);
- }
- }
- //加入Test1
- @Configuration
- @Import(value = {MybatisConfig.class, Test1.class})
- public class JavaConfig {
-
- public static void main(String[] args) {
- ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class);
- for (String str : ac.getBeanDefinitionNames()) {
- System.out.println(str);
- }
- }
- }
观察结果发现ab同样注入到spring中了
javaConfig
com.test.config.MybatisConfig
ab
用法4普通类
- //将Ab类加入
- @Configuration
- @Import(value = {MybatisConfig.class, Ab.class})
- public class JavaConfig {
-
- public static void main(String[] args) {
- ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class);
- for (String str : ac.getBeanDefinitionNames()) {
- System.out.println(str);
- }
- }
- }
观察结果Ab类同样注入到spring中了
javaConfig
com.test.config.MybatisConfig
com.test.config.Ab