Java – fields in Guice inject class are not created by Guice

I have a class where I create myself in my own code:

class StarryEyes {
   @Inject MyValidator validator;

   public StarryEyes(String name) {
      //..
   }

   public doSomething() {
      // validator is NULL
   }
}

I want Guice to inject an instance of a validator with an @ singleton annotation I have a module loaded at startup that contains the following lines:

bind(MyValidator.class);

However, it does not seem to work because the verifier is always empty I tried many variants, such as:

bind(MyValidator.class)toInstance(new MyValidator());

Or something like that Isn't this how Guice should work?

Solution

In general, Guice needs to create objects to inject them If you just called the new starryeyes (name), Guice won't look at the object, so you can't inject it One thing you can do is call inject. On the object after it is created injectMembers(obj). However, I do not recommend that you avoid referencing injectors in your code

What you really want is assisted inject With assisted inject, you can declare such a constructor for your class:

@Inject public StarryEyes(MyValidator validator,@Assisted String name)

This means that the verifier is the parameter Guice should inject, and name must be "auxiliary" (that is, provided when creating the instance)

Then, you will create an interface as follows:

public interface StarryEyesFactory {
  StarryEyes create(String name);
}

Guice can implement the factory for you through assisted inject You bind like this:

bind(StarryEyesFactory.class).toProvider(
    FactoryProvider.newFactory(StarryEyesFactory.class,StarryEyes.class));

Then, you can inject starryeyesfactory wherever you want to create its instance You used to call the new starryeyes (name), now you can call starryeyesfactory create(name). When create (name) is invoked in a factory, it will use the name and pass it to the constructor and provide the binding verifier itself.

Starting with Guice 3, you can use factorymodulebuilder:

install(new FactoryModuleBuilder().build(StarryEyesFactory.class));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>