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

 

posted on 2021-11-21 10:26  有点懒惰的大青年  阅读(698)  评论(0编辑  收藏  举报