2016-01-15 25 views
0

我想为使用泛型的两个模型类的代码实现。试图注入两个存储库与通用实施失败

我有两个模型类:

@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 
} 

现在,我试图注入两个服务如下:

@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?

回答

1

如果您使用Guice进行注射,您应该将接口绑定到模块配置中的实现类。如果你使用spring context,你应该在spring config中定义你的repository bean。

0

我能够通过创建一个更常见的父模型类smsInfo和emailInfo来解决问题如下:

@MappedSuperclass 
public class CommunicationInfo 
{ 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Column(name = Constants.ID_COLUMN) 
    protected Long id; 
} 

,并从两个类SmsInfo和EmailInfo扩展它。

之后,我得按如下方式使用库扩展以及为通用型:它采用同样的方式在其他地方以及

public interface CommunicationInfoRepository <Info extends CommunicationInfo> extends JpaRepository<Info, Long> 
{ 

} 

感谢大家的回应。