Spring 一个接口有多个实现的依赖注入
Spring dependency injection with multiple implementation for an interface
因此,此接口有 2 个实现。我想用接口的所有实现和 return 满足条件的实现对象验证输入。
接口:
interface SomeInterface {
boolean someCheck(int n);
}
实施 1:
public class SomeClass implements SomeInterface {
public boolean someCheck(int n) {
// returns true if n is less than 10
}
}
实施 2:
public class AnotherClass implements SomeInterface {
public boolean someCheck(int n) {
// returns true if n is greater than 10
}
}
我可以在这里使用依赖注入概念吗?
假设两个实现都是spring beans,你可以在列表中注入两个实现:
public class Validator {
@Autowired
private List<SomeInterface> allImplementations;
public boolean validate(int n) {
for(SomeInterface impl : allImplementations) {
if(!impl.someCheck(n)) {
return false;
}
}
return true; // all validations passed
}
}
因此,此接口有 2 个实现。我想用接口的所有实现和 return 满足条件的实现对象验证输入。
接口:
interface SomeInterface {
boolean someCheck(int n);
}
实施 1:
public class SomeClass implements SomeInterface {
public boolean someCheck(int n) {
// returns true if n is less than 10
}
}
实施 2:
public class AnotherClass implements SomeInterface {
public boolean someCheck(int n) {
// returns true if n is greater than 10
}
}
我可以在这里使用依赖注入概念吗?
假设两个实现都是spring beans,你可以在列表中注入两个实现:
public class Validator {
@Autowired
private List<SomeInterface> allImplementations;
public boolean validate(int n) {
for(SomeInterface impl : allImplementations) {
if(!impl.someCheck(n)) {
return false;
}
}
return true; // all validations passed
}
}