Autowire all beans for a specific type
这篇文章是参考 【spring自动注入接口的多个实现类(结合策略设计模式)】 得来的。
按里面的内容敲了一下代码,总是有错误,然后自己又搜索一下,得到了正确结果:
图片来源:https://www.baeldung.com/spring-dynamic-autowire
完整代码如下:
- 策略接口:
public interface DiscountStrategy {
String type();
double discount(double fee);
}
-
策略具体实现类:
- 调用接口:
public interface DiscountStrategyService {
double discount(String type, double fee) ;
}
- 接口实现:
@Service
public class DiscountStrategyServiceImpl implements DiscountStrategyService {
private final Map<String, DiscountStrategy> map;
// Besides standard single-field autowiring,
// Spring gives us an ability to collect all beans that are implementations of the specific interface into a Map:
@Autowired
public DiscountStrategyServiceImpl(List<DiscountStrategy> list) {
map = list.stream().collect(Collectors.toMap(DiscountStrategy::type, Function.identity(), (oldV, newV)-> newV));
}
@Override
public double discount(String type, double fee) {
DiscountStrategy ds = map.get(type);
if (ds == null) {
return -1;
}
return ds.discount(fee);
}
}
这里的构造函数要加上@Autowired
才正确
- 测试类:
@RunWith(SpringRunner.class)
@SpringBootTest
public class DiscountStrategyServiceTest {
@Autowired
private DiscountStrategyService service;
@org.junit.Test
public void testDiscountStrategy() {
double fee = 100;
System.out.println(service.discount("normal", fee));
System.out.println(service.discount("vip", fee));
System.out.println(service.discount("svip", fee));
}
}
- 输出结果:
99.0
80.0
50.0
如果总是注入失败,查看扫描的包是否包括strategty接口和实现类