Java Google Guice辅助注入对象为空
我需要在运行时使用用户定义的数据创建对象。为此,我使用了 google guice协助注入。但当我运行测试时,它抛出Java Google Guice辅助注入对象为空,java,guice,Java,Guice,我需要在运行时使用用户定义的数据创建对象。为此,我使用了 google guice协助注入。但当我运行测试时,它抛出null指针异常。请告诉我哪里出错 IArtifacts界面 public interface IArtifacts { MavenMetaDataXMLDTO getArtifactsVersions(); } public interface ArtifactsFactory { IArtifacts create(ProductProfile produ
null
指针异常。请告诉我哪里出错
IArtifacts界面
public interface IArtifacts {
MavenMetaDataXMLDTO getArtifactsVersions();
}
public interface ArtifactsFactory {
IArtifacts create(ProductProfile productProfile);
}
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;
}
}
工件工厂界面
public interface IArtifacts {
MavenMetaDataXMLDTO getArtifactsVersions();
}
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());
}
}
private Injector injector=Guice.createInjector(new MYModule());//where implemented configuration
@Inject
private ArtifactsFactory artifactsFactory=injector.getInstance(ArtifactsFactory.class);
休息终点
@GET
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public String getartifacts(){
new TestArtifacts().getdata();
}
您在Rest端点类中自己创建了TestArtifacts类的实例,但所有类都需要由Guice框架而不是您创建 那么,当您使用新工具创建类时,Guice框架应该如何向类中注入一些东西呢?您还需要将类TestArtifacts注入Rest端点,并且您的Rest端点也必须由Guice创建 更新: 也许这个链接会对你有所帮助
我能够通过向下面的TestArtifacts.java类添加以下代码片段来修复它 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());
}
}
private Injector injector=Guice.createInjector(new MYModule());//where implemented configuration
@Inject
private ArtifactsFactory artifactsFactory=injector.getInstance(ArtifactsFactory.class);
谢谢你的快速回复。你有样品可供参考吗。