ImportSelector介紹

參考博客: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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章