小编典典

Spring Boot自动装配具有多种实现的接口

spring-boot

在普通的Spring中,当我们想自动连接一个接口时,我们在Spring上下文文件中定义它的实现。那Spring
Boot呢?我们怎样才能做到这一点?目前,我们仅自动装配不是接口的类。这个问题的另一部分是关于在Spring启动项目中的Junit类中使用类。例如,如果我们要使用CalendarUtil,则如果我们自动连接CalendarUtil,它将抛出空指针异常。在这种情况下我们该怎么办?我现在刚刚使用“新”进行了初始化…


阅读 610

收藏
2020-05-30

共1个答案

小编典典

使用@Qualifier批注来区分同一接口的bean
请查看Spring Boot 文档。
此外,要注入同一接口的所有bean,只需 自动装配 List接口即可
(在Spring / Spring Boot / SpringBootTest中以相同的方式),
如下所示:

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
}

public interface MyService {

    void doWork();

}

@Service
@Qualifier("firstService")
public static class FirstServiceImpl implements MyService {

    @Override
    public void doWork() {
        System.out.println("firstService work");
    }

}

@Service
@Qualifier("secondService")
public static class SecondServiceImpl implements MyService {

    @Override
    public void doWork() {
        System.out.println("secondService work");
    }

}

@Component
public static class FirstManager {

    private final MyService myService;

    @Autowired // inject FirstServiceImpl
    public FirstManager(@Qualifier("firstService") MyService myService) {
        this.myService = myService;
    }

    @PostConstruct
    public void startWork() {
        System.out.println("firstManager start work");
        myService.doWork();
    }

}

@Component
public static class SecondManager {

    private final List<MyService> myServices;

    @Autowired // inject MyService all implementations
    public SecondManager(List<MyService> myServices) {
        this.myServices = myServices;
    }

    @PostConstruct
    public void startWork() {
        System.out.println("secondManager start work");
        myServices.forEach(MyService::doWork);
    }

}

}
2020-05-30