1 注解定义
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {
Class<?>[] value();
}
@Import注解由@Target({ElementType.TYPE})限制只能用在类上;
@Import注解用来导入配置类或者一些需要前置加载的类到IOC容器中。
2 @Import使用
2.1 直接填入需要加载的类
@Import({ 类名.class , 类名.class... })
示例:
public class Consumer {
public void consume(String str) {
System.out.println("INFO:" + str);
}
}
@SpringBootApplication
@Import(Consumer.class)
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerApplication.class, args);
}
}
@SpringBootTest(classes = ProducerApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class ConsumerTest {
@Autowired
private Consumer consumer;
@Test
public void consume() {
consumer.consume("CONSUME");
}
}
2.2 implements ImportSelector
实现ImportSelector接口,返回值是导入到容器中的组件全类名。
示例:
public class ConsumerImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
return new String[]{"com.zhao.service.Consumer"};
}
}
@SpringBootApplication
@Import(ConsumerImportSelector.class)
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerApplication.class, args);
}
}
2.3 implements ImportBeanDefinitionRegistrar
实现ImportBeanDefinitionRegistrar接口,在方法内进行bean注册。
示例:
public class ConsumerRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
//定义bean
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Consumer.class);
//注册bean
registry.registerBeanDefinition("consumer", rootBeanDefinition);
}
}
@SpringBootApplication
@Import(ConsumerRegistrar.class)
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerApplication.class, args);
}
}