jdk:1.8 springboot:2.0.2
@Import 該註解的方式爲 引入一個類或者多個類到spring容器內;
//在spring掃描不到的包裏面定義一個類 public class Broker { public void testBroker() { System.out.println("Broker.testBroker"); } }
//在spring掃描到的包裏定義一個類,例如controller中: @RestController @Import(Broker.class) public class UserController { @Autowired Broker broker; @GetMapping("/get") public String get() { broker.testBroker(); return "success"; } }
http://localhost:8080/get 訪問 結果爲:Broker.testBroker 當前表示的是:Broker被加載到spring中能夠 被定義調用
//若是定義的爲接口的話,能夠@Import({實現類1.class, 實現類2.class}) 這種方式會報錯 ield demoService in com.apple.controller.UserController required a single bean, but 2 were found: public interface DemoService { public void test(); } public class DemoServiceImpl implements DemoService { @Override public void test() { System.out.println("DemoServiceImpl.test"); } } public class DemoService2Impl implements DemoService { @Override public void test() { System.out.println("DemoService2Impl.test"); } } @RestController @Import({DemoServiceImpl.class, DemoService2Impl.class}) public class UserController { @Autowired DemoService demoService; @GetMapping("/get") public String get() { demoService.test(); return "success"; } }
//對於上面的報錯信息能夠更改成: @Service("demo") public class DemoServiceImpl implements DemoService { @Override public void test() { System.out.println("DemoServiceImpl.test"); } } @RestController @Import({DemoServiceImpl.class, DemoService2Impl.class}) public class UserController { @Resource(name="demo") DemoService demoService; @GetMapping("/get") public String get() { demoService.test(); return "success"; } }
//上面的方式使用起來挺方便的,可是若是是一個接口有兩種實現,上面的方法,要在實現類中定義類的別名,也能夠在一個類中定義兩種實現的別名 public class MyImportDefinitionRegister implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) { BeanDefinition definition1 = BeanDefinitionBuilder.rootBeanDefinition(DemoServiceImpl.class).getBeanDefinition(); beanDefinitionRegistry.registerBeanDefinition("aa", definition1); BeanDefinition definition2 = BeanDefinitionBuilder.rootBeanDefinition(DemoService2Impl.class).getBeanDefinition(); beanDefinitionRegistry.registerBeanDefinition("bb", definition2); } } @RestController @Import(MyImportDefinitionRegister.class) public class UserController { @Resource(name = "aa") DemoService demoService; @GetMapping("/get") public String get() { demoService.test(); return "success"; } }
若是自定義一個註解,註解中定義@Import,則對應的該類也會到入 對應的類信息 @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Import(ImportDirect.class) public @interface MyAnnocation { public String value() default "default"; } @RestController @MyAnnocation public class UserController { @Autowired ImportDirect importDirect; @GetMapping("/get") public String get() { importDirect.test(); return "success"; } }