Spring Boot自动装配具有多种实现的接口 [英] Spring boot autowiring an interface with multiple implementations

查看:297
本文介绍了Spring Boot自动装配具有多种实现的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In normal Spring, when we want to autowire an interface, we define it's implementation in Spring context file. What about Spring boot? how can we achieve this? currently we only autowire classes that are not interfaces. Another part of this question is about using a class in a Junit class inside a Spring boot project. If we want to use a CalendarUtil for example, if we autowire CalendarUtil, it will throw a null pointer exception. What can we do in this case? I just initialized using "new" for now...

推荐答案

使用@Qualifier批注用于区分同一接口的bean
看一下Spring Boot

Use @Qualifier annotation is used to differentiate beans of the same interface
Take look at Spring Boot documentation
Also, to inject all beans of the same interface, just autowire List of interface
(The same way in Spring / Spring Boot / SpringBootTest)
Example below:

@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);
    }

}

}

对于问题的第二部分,请参见以下有用的答案第一/

For the second part of your question, take look at this useful answers first / second

这篇关于Spring Boot自动装配具有多种实现的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆