关于java:Import的使用

28次阅读

共计 1965 个字符,预计需要花费 5 分钟才能阅读完成。

作用 :
1)@Import:源码的正文中曾经表明, 它的性能等于 @bean,<import/>。能够引入一个类(这个类能够是一般类, 也能够是 @Configuraion/Component 润饰的类), 并且退出到 Spring 容器中, 程序中能够间接 @autowired 注入
2) 前两种形式退出容器时,bean id 为全限定类名, 第三种形式能够自定义 id
第三种形式的长处在于能够自定义创立 bean 的过程。

1. 间接引入对应类的 Class 对象,

//MyImportSelector,MyImportBeanDefinitionRegistrar 别离实现了两个接口
@Import({TestA.class,TestB.class,MyImportSelector.class,MyImportBeanDefinitionRegistrar.class})
public class SpringConfig { }

public class TestA {public TestA() {System.out.println("执行 testA 的无参构造方法");
    }

    public void funTestA() {System.out.println("执行 testA 中的 funTestA 办法");
    }

}
 
public class TestB {public TestB() {System.out.println("执行 TestB 的无参构造方法");
    }

    public void funTestB() {System.out.println("执行 TestB 中的 funTestB 办法");
    }

}

2. 实现 ImportSelector 接口
1) 能够返回空数组, 然而不能返回 null, 否则会报空指针异样

/**
 * 实现 ImportSelector, 重写办法 selectImports, 返回须要引入的类, 并创立实例, 退出 spring 容器
 */
public class MyImportSelector implements ImportSelector {public MyImportSelector() {System.out.println("MyImportSelector 构造方法");
    }


    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {return new String[]{"com.lagou.edu.testimport.TestC"};
    }
    
}

3. 实现 ImportBeanDefinitionRegistrar 接口

public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {public MyImportBeanDefinitionRegistrar() {System.out.println("执行 MyImportBeanDefinitionRegistrar 的构造方法");
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 指定要注册的 bean 信息
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(TestD.class);
        // 注册 bean, 并指定 bean 的 id
        registry.registerBeanDefinition("testD", rootBeanDefinition);
    }
}

测试案例

@Test
public void test3() {AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfig.class);
   
    
    TestA testA =(TestA) ac.getBean("com.lagou.edu.testimport.TestA");
    testA.funTestA();

    TestB testB =(TestB) ac.getBean("com.lagou.edu.testimport.TestB");
    testB.funTestB();

    TestC testC =(TestC) ac.getBean("com.lagou.edu.testimport.TestC");
    testC.funTestC();

    // 注册 bean 时指定了 bean 的 id,TestD testD =(TestD) ac.getBean("testD");
    testD.funTestD();}

正文完
 0