2016-01-15 27 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> 
{ 

} 

感謝大家的迴應。