gpt4 book ai didi

java - 多种类型的相同接口(interface)

转载 作者:行者123 更新时间:2023-11-30 05:50:31 24 4
gpt4 key购买 nike

我有一个接口(interface),并且有一些实现。每个实现都属于某种类型。我希望当我使用 Autowiring 时,我能够获得特定类型的所有实现。我该怎么做?

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){}

}

我只想获取 impl1OfType1impl2OfType1。而且不是全部实现。在其他地方,我只想获取 impl1OfType2impl2OfType2

更具体的例子 -

    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){}

}

最佳答案

解决方案是使用 @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 擅长处理它们。例如,它只会注入(inject) DogCreatorCatCreator进入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) { }
}

更新2

您可以编写标记接口(interface),将现有实现分解为逻辑组。

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);
}

}

关于java - 多种类型的相同接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53987208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com