2017-08-24 64 views
0

我需要runtime.TO來創建用戶定義的數據對象一樣,我是用輔助inject.But當我運行我的測試 谷歌吉斯它拋出null指針exception.Please讓我知道我犯了錯誤。谷歌吉斯輔助進樣對象爲空

IArtifacts接口

public interface IArtifacts { 

    MavenMetaDataXMLDTO getArtifactsVersions(); 
} 

ArtifactsService.java

public class ArtifactsService implements IArtifacts { 

    private ProductProfile productProfile; 

    @Inject 
    public ArtifactsService(@Assisted ProductProfile productProfile){ 
     System.out.println(productProfile.getArtifactManagementURL()); 
     this.productProfile=productProfile; 
    } 

    @Override 
    public MavenMetaDataXMLDTO getArtifactsVersions() { 

     System.out.println(productProfile.getArtifactManagementURL()); 
     return null; 
    } 
} 

ArtifactsFactory接口

public interface ArtifactsFactory { 

    IArtifacts create(ProductProfile productProfile); 
} 

模塊類

@Override 
    protected void configure() { 
    install(new FactoryModuleBuilder().implement(IArtifacts.class,ArtifactsService.class).build(ArtifactsFactory.class)); 
} 

TestArtifacts.java

public class TestArtifacts { 

    @Inject // this obj is null 
    private ArtifactsFactory artifactsFactory; 

    private IArtifacts s; 

    public TestArtifacts(){ 

    } 

    public void getdata(){ 
     //Pass custom data to factory 
     this.s=artifactsFactory.create(Products.QA.get()); 
     System.out.println(s.getArtifactsVersions()); 
    } 


} 

REST端點

@GET 
    @Path("/test") 
    @Produces(MediaType.APPLICATION_JSON) 
    public String getartifacts(){ 
     new TestArtifacts().getdata(); 
    } 

回答

1

我能解決它添加下面的代碼片斷TestArtifacts.java類下面

TestArtifacts.java

private Injector injector=Guice.createInjector(new MYModule());//where implemented configuration 

    @Inject 
    private ArtifactsFactory artifactsFactory=injector.getInstance(ArtifactsFactory.class); 
1

您在REST端點創建類TestArtifacts的實例,你自己班級,但你的班級es需要由Guice Framework創建,而不是由您創建。

那麼Guice Framework如何在你的類中使用new創建它們的時候應該如何注入呢?您還需要將類TestArtifacts注入您的Rest端點,您的Rest端點也必須由Guice創建。

更新:

也許這個鏈接可以幫助你

https://sites.google.com/a/athaydes.com/renato-athaydes/posts/jersey_guice_rest_api

+0

感謝您的快速回復。你有任何樣品可供參考。 – gihan

+0

看到我的更新。我添加了一個鏈接 –