1、ImportSelector实现类

package com.example.selectors;

import com.example.mapper.impl.UserMapperImpl;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;

public class MyImportSelector implements ImportSelector {

    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        // 后续Spring会根据返回的字符串,通过反射实例化对象,并放入容器中
        return new String[] {UserMapperImpl.class.getName()};
    }

}

/*
	根据 selectImports() 方法返回的全限定路径名 注册Bean
*/


2、配置类

package com.example.config;

import com.example.annotations.LaeScan;
import org.springframework.context.annotation.*;

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

}


3、测试类

package com.example.test;

import com.example.config.AppConfiguration2;
import com.example.mapper.UserMapper;
import com.example.mapper.impl.UserMapperImpl;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test2 {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfiguration.class);
        // 判断 UserMapperImpl 是否已经注册到 Spring 容器当中
        UserMapper userMapper = applicationContext.getBean(UserMapperImpl.class);
        userMapper.print();
    }
}


4、注解优化

/* 
 * 自定义一个注解,将 @Import() 放在自定义注解中。
 * 再将 @CustomImportSelector 放到 AppConfiguration 类上
 */
    
package com.example.annotations;

import com.example.selectors.MyImportSelector;
import org.springframework.context.annotation.Import;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(MyImportSelector.class)
public @interface CustomImportSelector {
}