CDI模糊分辨率与扩展类

时间:2018-04-13 05:18:38

标签: java-ee cdi

我需要在各种bean中注入CacheService,并维护名为CacheService的单ResourceCacheService扩展名。

interface CacheService{}
@Default
class CacheServiceImpl implements CacheService{}
@Singleton
class ResourceCacheService extends CacheServiceImpl{}

或者更好:

interface ResourceCacheService extends CacheService{}
@Singleton
class ResourceCacheServiceImpl extends CacheServiceImpl{}

无论哪种方式,我都会得到一个模棱两可的例外。如何在需要的地方注入CacheService的新实例,并创建Singleton版本的实例?

更新 - 添加了例外

Caused by: org.apache.openejb.OpenEJBRuntimeException: org.apache.webbeans.exception.WebBeansDeploymentException: javax.enterprise.inject.AmbiguousResolutionException: There is more than one Bean with type com.project.cache.CacheServiceQualifiers: [@javax.enterprise.inject.Default()]

ResourceCacheService, WebBeansType:MANAGED, Name:null, API Types:[com.project.web.ResourceCacheService,com.project.cache.CacheService,java.lang.Object,com.project.cache.CacheServiceImpl], Qualifiers:[javax.enterprise.inject.Default,javax.enterprise.inject.Any] from file:/application/webapps/ROOT/WEB-INF/classes/com/project/web/ResourceCacheService.class
CacheServiceImpl, WebBeansType:MANAGED, Name:null, API Types:[com.project.cache.CacheService,java.lang.Object,com.project.cache.CacheServiceImpl], Qualifiers:[javax.enterprise.inject.Default,javax.enterprise.inject.Any] from file:/application/webapps/ROOT/WEB-INF/classes/com/project/cache/CacheServiceImpl.class

1 个答案:

答案 0 :(得分:1)

基本上,你有一个继承链C扩展B扩展A并希望在不同的场景中使用C和B.如果没有进一步限定类,则无法完成此操作,因此要么创建不同的继承方案:

interface CacheServiceBase
StandardCacheService implements CacheServiceBase
GlobalCacheService implements CacheServiceBase

// Injection of different things which do *not* extend each other
@Inject StandardCacheService
@Inject GlobalCacheService

或使用限定符注释来进一步区分实现。请参阅此处如何操作:https://docs.jboss.org/weld/reference/latest/en-US/html/injection.html