java - 尝试注入(inject)两个具有通用实现的存储库失败

标签 java spring generics dependency-injection javabeans

我正在尝试使用泛型为两个模型类编写实现代码。

我有两个模型类:

@Entity
@Table(name = "SMS_INFO")
public class SmsInfo
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = Constants.ID_COLUMN)
    private Long smsInfoId;

    // other fields and public getters
}

EmailInfo 也有类似的模型类。

现在,对于这两个类,我尝试创建通用存储库和服务类,如下所示:

public interface InfoRepository <Info> extends JpaRepository<Info, Long> {}

public interface CommunicationInfoServiceI <Info>
{
    // Some abstract methods
}

@Named
public class CommunicationInfoServiceImpl<Info> implements CommunicationInfoServiceI<Info>
{
    @Inject
    private InfoRepository<Info> infoRepository;

    // Other implementations
}

现在,我尝试注入(inject)这两个服务,如下所示:

@Named
@Singleton
public class ServiceFactory
{
    @Inject
    private CommunicationInfoServiceI<SmsInfo> smsInfoService;

    @Inject
    private CommunicationInfoServiceI<EmailInfo> emailInfoService;

    // Other Getter methods
}

但我收到以下错误:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'serviceFactory': Injection of autowired dependencies failed; 
    nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private CommunicationInfoServiceI ServiceFactory.smsInfoService; 
    nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'communicationInfoServiceImpl': Injection of autowired dependencies failed; 
    nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private InfoRepository CommunicationInfoServiceImpl.infoRepository; 
    nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'infoRepository': Invocation of init method failed; 
    nested exception is java.lang.IllegalArgumentException: Not an managed type: class java.lang.Object

有人可以帮帮我吗,我被困在这里了?

提前致谢。

Note: I have tried removing all injections of generic classes and left InfoRepository as it is, it is still giving the same error. I think it shouldn't be because of serviceFactory, it should be something to do with JPARepository, initially it might be trying to inject it and failing in doing, as JVM might not be knowing about 'Info' type. Can we do something for this?

最佳答案

如果您使用 Guice 进行注入(inject),您应该将接口(interface)绑定(bind)到模块配置中的实现类。如果您使用 spring 上下文,您应该在 spring 配置中定义您的存储库 bean。

关于java - 尝试注入(inject)两个具有通用实现的存储库失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34812855/

相关文章:

javascript - PhantomJS 运行 JS 的 HTML 页面结果中如何获取嵌入的 JSON 对象并将其传递给 java 代码?

java - Spring MVC 中资源包的最佳方法是什么?

spring - 事务服务中的 ConstraintViolationException 没有回滚

java - 在 spring boot 项目中使用 spring eclipse sts 逆向工程数据库表

java - 如何在运行时获取泛型类型?

c# - 使用泛型进行显式转换

java - XML 将节点值解析为字符串

java - Spring的存储过程,解析结果Map

c# - 基于通用类型的正确实现属性的方法

java - 系统升级后jvm崩溃