gihan-maduranga
gihan-maduranga

Reputation: 4801

Google Guice Assisted Inject object is null

I need to create objects with user defined data at runtime.TO do that i have used google guice assisted inject.But when i run my test it throws null pointer exception.Please let me know where i made the mistake.

IArtifacts Interface

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);
}

Module Class

@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();
    }

Upvotes: 1

Views: 623

Answers (2)

gihan-maduranga
gihan-maduranga

Reputation: 4801

I was able to fix it adding following code snippet to below TestArtifacts.java class

TestArtifacts.java

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

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

Upvotes: 1

Michael Meyer
Michael Meyer

Reputation: 2184

you created an Instance of the class TestArtifacts on your own in your Rest Endpoint class but all of your classes need to be created by the Guice Framework and not by you.

So how should the Guice Framework inject something into your class when you create them with new? You also need to inject the class TestArtifacts into your Rest Endpoint and your Rest Endpoint has to be created by Guice too.

Update:

Maybe this link will help you

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

Upvotes: 1

Related Questions