參考博客:https://blog.csdn.net/elim168/article/details/88131614
在@Configuration
標註的Class上可以使用@Import
引入其它的配置類,其實它還可以引入org.springframework.context.annotation.ImportSelector
實現類。
ImportSelector接口只定義了一個selectImports()
,用於指定需要註冊爲bean的Class名稱。
當在@Configuration
標註的Class上使用@Import
引入了一個ImportSelector實現類後,會把實現類中返回的Class名稱都定義爲bean。
1.簡單示例:
a.假設現在有一個接口HelloService,需要把所有它的實現類都定義爲bean,而且它的實現類上是沒有加Spring默認會掃描的註解的,比如@Component
、@Service
等。
b.定義了一個ImportSelector實現類HelloImportSelector,直接指定了需要把HelloService接口的實現類HelloServiceA和HelloServiceB定義爲bean。
c.定義了@Configuration
配置類HelloConfiguration,指定了@Import
的是HelloImportSelector。
HelloService:
package com.cy.service; public interface HelloService { void doSomething(); }
HelloServiceA:
package com.cy.service.impl; import com.cy.service.HelloService; public class HelloServiceA implements HelloService { @Override public void doSomething() { System.out.println("Hello A"); } }
HelloServiceB:
package com.cy.service.impl; import com.cy.service.HelloService; public class HelloServiceB implements HelloService { @Override public void doSomething() { System.out.println("Hello B"); } }
HelloImportSelector:
package com.cy.service.impl; import org.springframework.context.annotation.ImportSelector; import org.springframework.core.type.AnnotationMetadata; public class HelloImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[]{HelloServiceA.class.getName(), HelloServiceB.class.getName()}; } }
HelloConfiguration:
package com.cy.config; import com.cy.service.impl.HelloImportSelector; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({HelloImportSelector.class}) public class HelloConfiguration { }
IndexController進行測試:
@Controller public class IndexController { @Autowired private List<HelloService> helloServices; @ResponseBody @RequestMapping("/testImportSelector") public void testImportSelector() { helloServices.forEach(helloService -> helloService.doSomething()); } }
console:
Hello A
Hello B