Google Guice Assisted Inject对象为空

时间:2017-08-24 07:39:49

标签: java guice

我需要在runtime.TO做我已经使用过的用户定义数据的对象 google guice辅助注射。但是当我运行我的测试时它会抛出null指针异常。请让我知道我犯了哪个错误。

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 Interface

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 ENDPOINT

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

2 个答案:

答案 0 :(得分:1)

您在Rest Endpoint类中自己创建了一个类TestArtifacts的实例,但您的所有类都需要由Guice Framework创建,而不是由您创建。

那么当您使用new创建它们时,Guice Framework应该如何为您的类注入一些东西?您还需要将类TestArtifacts注入到您的Rest Endpoint中,而您的Rest Endpoint也必须由Guice创建。

更新

也许这个链接会帮助你

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

答案 1 :(得分:1)

我能够修复它,将以下代码片段添加到TestArtifacts.java类

下面

<强> TestArtifacts.java

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

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