+-

在普通的 Spring中,当我们想要自动装配接口时,我们在Spring上下文文件中定义它的实现.春季靴子怎么样?我们怎样才能做到这一点?目前我们只对不是接口的类进行自动装配.
这个问题的另一部分是关于在Spring启动项目中使用Junit类中的类.例如,如果我们想使用CalendarUtil,如果我们自动装配CalendarUtil,它将抛出一个空指针异常.在这种情况下我们能做些什么?我刚刚用“new”初始化了…
这个问题的另一部分是关于在Spring启动项目中使用Junit类中的类.例如,如果我们想使用CalendarUtil,如果我们自动装配CalendarUtil,它将抛出一个空指针异常.在这种情况下我们能做些什么?我刚刚用“new”初始化了…
最佳答案
使用@Qualifier注释用于区分同一接口的bean
看一下Spring Boot documentation
另外,要注入相同接口的所有bean,只需autowire List of interface
(Spring / Spring Boot / SpringBootTest中的方式相同)
示例如下:
看一下Spring Boot documentation
另外,要注入相同接口的所有bean,只需autowire List of interface
(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);
}
}
}
对于问题的第二部分,请看一下这个有用的答案first/second
点击查看更多相关文章
转载注明原文:Spring启动自动装配具有多个实现的接口 - 乐贴网