简介
本文介绍Spring注册Bean的方法:@Import+ImportSelector接口。
注册Bean的方法我写了一个系列,见:Spring注册Bean(提供Bean)-方法大全 – 自学精灵
方法概述
- 实现ImportSelector接口
- 实现它的selectImports方法(返回需要导入的组件的全类名数组;)
- 在启动类上添加:@Import(ImportSelector接口的实现类)
- 也可以放在在其他@Configuration标记的类上
实例
ImportSelector接口的实现类
package com.knife.selector; import org.springframework.context.annotation.ImportSelector; import org.springframework.core.type.AnnotationMetadata; import java.util.Set; //自定义逻辑返回需要导入的组件 public class MyImportSelector implements ImportSelector { //返回值,就是到导入到容器中的组件全类名 //AnnotationMetadata:当前标注@Import注解的类的所有注解信息 @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { //当前类的所有注解 Set<String> annotationTypes = importingClassMetadata.getAnnotationTypes(); System.out.println("当前配置类的注解信息:" + annotationTypes); //可以写多个,用逗号隔开 //不能返回null,不然会报NullPointException return new String[]{"com.knife.entity.MyBean"}; } }
要注册的类(Bean)
package com.knife.entity; public class MyBean { public String sayHello() { return "Hello World"; } }
导入注册类
法1:启动类
package com.knife; import com.knife.selector.MyImportSelector; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Import; @SpringBootApplication @Import({MyImportSelector.class}) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
法2:@Configuration 标记的类
其实,只要是注册到Spring容器中的类就可以,但一般用@Configuration。
package com.knife.config; import com.knife.selector.MyImportSelector; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({MyImportSelector.class}) public class MyBeanImportConfiguration { }
测试
package com.knife.controller; import com.knife.entity.MyBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @Autowired private MyBean myBean; @GetMapping("/test") public String test() { return myBean.sayHello(); } }
结果
请先
!