SpringBoot复习:(23)ImportSelector的用法

功能: 定一一个字符串数组,每个元素都是一个类的全限定名(包名+类名),把这些类的实例注册到Spring 容器。
一、定义要注册的类:

package cn.edu.tju.service;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

import java.util.Date;


public class DemoService {

    public String getTime(){
        return "now is " + new Date().toLocaleString();
    }
}

package cn.edu.tju.service;

public class TestService {
}

二、自定义ImportSelector实现ImportSelector,实现selectImports方法:

package cn.edu.tju.config;

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;


public class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{"cn.edu.tju.service.DemoService", "cn.edu.tju.service.TestService"};
    }
}

selectImports方法返回的就是要注册的类的全限定名。
三、在配置类中导入MyImportSelector

package cn.edu.tju.config;


import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.io.IOException;
import java.io.Reader;

import static org.apache.ibatis.io.Resources.getResourceAsReader;

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

}

四、在容器中获取通过MyImportSelector注册的bean

package cn.edu.tju;

import cn.edu.tju.mapper.StudentMapper;
import cn.edu.tju.service.DemoService;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@SpringBootApplication
public class Start {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Start.class, args);
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        for(String str: beanDefinitionNames){
            //System.out.println(str);
        }
        DemoService demoService = context.getBean(DemoService.class);
        System.out.println(demoService.getTime());


    }
}

你可能感兴趣的:(SpringBoot,spring,boot,后端,java)