ImportSelector使用详解


版权声明

  • 本文原创作者:谷哥的小弟
  • 作者博客地址:http://blog.csdn.net/lfdfhl

ImportSelector使用详解_第1张图片

ImportSelector概述

利用@Import和ImportSelector可将组件批量添加至IoC容器

ImportSelector案例

在此,介绍ImportSelector使用案例。

定义ImportSelector

School、Teacher、Student是三个pojo类。

public class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        String school = "com.cn.pojo.School";
        String teacher = "com.cn.pojo.Teacher";
        String student = "com.cn.pojo.Student";
        String[] imports = {school,teacher,student};
        return imports;
    }
}

批量添加组件至IoC

@Import(MyImportSelector.class)
@Configuration
public class MyConfig {

}

测试

package com.cn;

import com.cn.pojo.School;
import com.cn.pojo.Student;
import com.cn.pojo.Teacher;
import com.cn.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootTest
class SpringBootTests {

    @Autowired
    // 获取IoC容器
    private ConfigurableApplicationContext configurableApplicationContext;
    @Test
    public void testBeans(){
        School school = configurableApplicationContext.getBean(School.class);
        System.out.println(school);
        Teacher teacher = configurableApplicationContext.getBean(Teacher.class);
        System.out.println(teacher);
        Student student = configurableApplicationContext.getBean(Student.class);
        System.out.println(student);
    }

}

你可能感兴趣的:(Spring,SpringBoot,Import,注解)