我有一个接口,并且为此有一些实现。每个实现都属于某种类型。 我希望当我使用自动装配时,我能够获得特定类型的所有实现。我该怎么办?
public interface someInterface{}
public class impl1OfType1 implements someInterface{}
public class impl2OfType1 implements someInterface{}
public class impl1OfType2 implements someInterface{}
public class impl2OfType2 implements someInterface{}
public class someClass{
@autowired
public someClass(List<someInterface> interfaceList){}
}
我只想获取impl1OfType1
和impl2OfType1
。并非全部执行。
而在其他地方,我只想获取impl1OfType2
和impl2OfType2
。
更具体的示例-
public interface EntityCreator{
createEntity();
}
@Component
public class DogCreator implements entityCreator{}
@Component
public class CatCreator implements entityCreator{}
@Component
public class CarCreator implements entityCreator{}
@Component
public class TruckCreator implements entityCreator{}
@Component
public class AnimalsFactory{
@Autowired
public AnimalsFactory(List<EntityCreator> creators){}
}
答案 0 :(得分:1)
解决方案将使用@Qualifier
。
@Component
@Qualifier("place1")
class Impl1OfType2 implements SomeInterface {}
@Component
@Qualifier("place1")
class Impl2OfType2 implements SomeInterface {}
@Service
class SomeClass {
@Autowired
public SomeClass(@Qualifier("place1") List<SomeInterface> interfaceList) {
System.out.println(interfaceList);
}
}
我略微更改了名称以遵守Java约定。它们仍然有点笨拙且无上下文。
您可能会使用泛型,Spring善于处理它们。例如,它将仅将DogCreator
和CatCreator
注入到List<EntityCreator<Animal>>
中。
interface Animal {}
interface Machine {}
interface EntityCreator<T> {}
@Component
class DogCreator implements EntityCreator<Animal> {}
@Component
class CatCreator implements EntityCreator<Animal> {}
@Component
class CarCreator implements EntityCreator<Machine> {}
@Component
class TruckCreator implements EntityCreator<Machine> {}
@Component
class AnimalsFactory {
@Autowired
public AnimalsFactory(List<EntityCreator<Animal>> creators) { }
}
您可以编写标记接口,将现有的实现分解为逻辑组。
interface AnimalCreator {}
interface EntityCreator<T> {}
@Component
class DogCreator implements EntityCreator, AnimalCreator {}
@Component
class CatCreator implements EntityCreator, AnimalCreator {}
@Component
class AnimalsFactory {
@Autowired
public AnimalsFactory(List<AnimalCreator> creators) {
System.out.println(creators);
}
}
答案 1 :(得分:0)
如果您通过上述注释更正了您的代码,并且我理解您的问题,那么我认为这可以解决您的问题。
public interface Someinterface<T extends someType> {}
public class someType{}
public class Type1 extends someType{}
public class Type2 extends someType{}
public class TypedInterface1 implements Someinterface<Type1> {}
public class TypedInterface2 implements Someinterface<Type2> {}
public class someClass{
@Autowired
public someClass(List<TypedInterface1> interfaceList){}
}
让我知道我是否回答了您的问题。