Google Guice Assisted Inject 对象为空



我需要在运行时使用用户定义的数据创建对象。要做到这一点,我已经用过了 谷歌吉斯辅助注射。但是当我运行测试时,它会抛出null指针异常。请让我知道我在哪里犯了错误。

内部接口

public interface IArtifacts {
MavenMetaDataXMLDTO getArtifactsVersions();
}

工件服务.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;
}
}

工件工厂接口

public interface ArtifactsFactory {
IArtifacts create(ProductProfile productProfile);
}

模块类

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

测试工件.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());
}

}  

休息端点

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

您在 Rest Endpoint 类中自行创建了类 TestArtifacts 的实例,但所有类都需要由 Guice 框架创建,而不是由您创建。

那么,当您使用 new 创建 Guice 框架时,Guice 框架应该如何为您的类注入一些东西呢?您还需要将类 TestArtifacts 注入到 Rest 端点中,并且您的 Rest 端点也必须由 Guice 创建。

更新:

也许这个链接会对你有所帮助

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

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

测试工件.java

private Injector injector=Guice.createInjector(new MYModule());//where implemented configuration
@Inject
private ArtifactsFactory artifactsFactory=injector.getInstance(ArtifactsFactory.class);

最新更新