Juice注入器抛出空指针异常

问题描述 投票:0回答:1

我试图学习谷歌汁。我有一个InstallConfigurationModule类,它具有创建typeA和TypeB对象所需的所有依赖关系。然后,得到一个类说类Car如下所示,我正在尝试进行构造函数注入。当调用run方法时,我会在system.out.println行获取空指针异常。我知道ModuleA,ModuleB对我在InstallConfigurationModulemodule中创建TypeA,TypeB时有所参考,如果我说Bind(TypeA.class)或Bind (TypeB.class),我得到google juice错误,'绑定到typeA或typeB已经配置'。

public class InstallConfigurationModule extends AbstractModule {

@Override
    protected void configure() {
        install(new ModuleA());
        install(new ModuleB());
    }
}
public class Car

{
  private Type A;
  private Type B;

@inject
  void SetCar(Type A, Type B)//not the constructor
 {
   this.A=A;
   this.B=B;
}

private void run()
{
  System.out.println(A.toString()) //throw null pointer exception
}

工作原理:

private void run()
    { 
     Injector injector = Guice.createInjector(new 
                         InstallConfigurationModule());

    TypeA typeA =injector.getInstance(TypeA.class);
      System.out.println(A.toString()) //works fine

    }

当我尝试不使用creatInjector时,为什么我会获得NPE。任何帮助赞赏。

PS:非常新的果汁。

java dependency-injection guice
1个回答
1
投票

我们假设我们有以下组件:

  • 一个类接口
public interface Type {}
  • 一个接口实现
public class TypeImpl implements Type {
    private String name;

    public TypeImpl(String name) {this.name = name;}

    public String getName() {return name;}

    @Override
    public String toString() {return name.toString();}
}
  • 配置模块
public class InstallConfigurationModule extends AbstractModule {
    @Override
    protected void configure() {
        super.configure();

        // new ModuleA()
        bind(Type.class).annotatedWith(Names.named("a")).toInstance((Type) new TypeImpl("a"));
        // new ModuleB()
        bind(Type.class).annotatedWith(Names.named("b")).toInstance((Type) new TypeImpl("b"));
    }
}

它不使用安装方法,但你可以使用它; configure方法使用Names.named API将TypeImpl标记为“a”,将另一个标记为“b”。

我们必须将@Named和@Inject注释放在Car类中

import com.google.inject.name.Named;

import javax.inject.Inject;

public class Car {
    private Type a;
    private Type b;

    @Inject
    public void setA(@Named("a") Type a) {
        this.a = a;
    }

    @Inject
    public void setB(@Named("b") Type b) {
        this.b = b;
    }

    public void methodIsCalled(){
        run();
    }

    private void run() {
        System.out.println(a.toString());
        System.out.println(b.toString());
    }
}

因此,注入器将知道如何配置Type实例。

最后,在main或configuration类中,我们有以下语句

public class MainClass {
    public static void main(String[] args){
        Injector injector = Guice.createInjector(new InstallConfigurationModule());
        Car car = injector.getInstance(Car.class);

        // method that it calss the run method
        car.methodIsCalled();
    }
}

这是输出

a
b
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.