功能: 定一一个字符串数组,每个元素都是一个类的全限定名(包名+类名),把这些类的实例注册到Spring 容器。
一、定义要注册的类:
package cn.edu.tju.service;import java.util.Arrays;
import java.util.List;public class MusicService {public List<String> getComposerList(){return Arrays.asList("Mozart", "Chopin");}
}
二、定义类实现DeferredImportSelector
package cn.edu.tju.config;import org.springframework.context.annotation.DeferredImportSelector;
import org.springframework.core.type.AnnotationMetadata;import java.util.ArrayList;
import java.util.List;public class MyDeferredImportSelector implements DeferredImportSelector {@Overridepublic String[] selectImports(AnnotationMetadata importingClassMetadata) {//return new String[]{"cn.edu.tju.service.MusicService"};return new String[0];}@Overridepublic Class<? extends Group> getImportGroup() {return MyGroup.class;}private static class MyGroup implements DeferredImportSelector.Group{AnnotationMetadata metadata;@Overridepublic void process(AnnotationMetadata metadata, DeferredImportSelector selector) {this.metadata = metadata;}@Overridepublic Iterable<Entry> selectImports() {List<Entry> list = new ArrayList<>();list.add(new Entry(this.metadata, "cn.edu.tju.service.MusicService"));return list;}}
}
三、在配置类中配置自定义的DeferredImportSelector
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({MyDeferredImportSelector.class})public class MyConfig {}
四、从容器中获取通过DeferredImportSelector注册的bean
package cn.edu.tju;import cn.edu.tju.mapper.StudentMapper;
import cn.edu.tju.service.DemoService;
import cn.edu.tju.service.MusicService;
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);MusicService musicService = context.getBean(MusicService.class);System.out.println(musicService.getComposerList());}
}