Spring Boot 自动装配具有多个实现的接口 [英] Spring boot autowiring an interface with multiple implementations
问题描述
在普通的 Spring 中,当我们想要自动装配一个接口时,我们在 Spring 上下文文件中定义它的实现.
In normal Spring, when we want to autowire an interface, we define it's implementation in Spring context file.
- Spring Boot 怎么样?
- 我们如何才能做到这一点?
目前我们只自动装配不是接口的类.
currently we only autowire classes that are not interfaces.
这个问题的另一部分是关于在 Spring boot 项目中使用 Junit 类中的类.
Another part of this question is about using a class in a Junit class inside a Spring boot project.
例如,如果我们想使用 CalendarUtil,如果我们自动装配 CalendarUtil,它将抛出空指针异常.在这种情况下我们能做什么?我刚刚使用new"初始化现在...
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 文档
另外,要注入同一接口的所有bean,只需autowire List
接口
(在 Spring/Spring Boot/SpringBootTest 中也是如此)
下面的例子:
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屋!