Inject instance in all objects using Guice - java

class A {
public A() {
}
}
class B {
#Inject
#Named("A")
private A a;
public B() {
}
public A getA() {
return a;
}
}
class AModule extends AbstractModule {
#Override
protected void configure() {
}
#Provides
#Singleton
#Named("A")
public A providesA() {
return new A();
}
}
We are doing like this:
AModule module = new AModule();
Injector injector = Guice.createInjector(module);
B b = injector.getInstance(B.class);
System.out.println(sample.getA());
But we have many classes with A as dependency and we don't want to add this code every time we create an instance.
So, is there any way to auto inject instance of A while creating instance of B?

It is (usually) not correct to create as many top-level Injectors as you suggest in your question. Injector creation is expensive, and once Guice has calculated your graph of dependencies, you should not need to calculate it all over again. In general there should be one top-level Injector across your application, and any other Injectors are either "child injectors" or parts of a separate and unrelated object graph.
In order from "worst" to "best":
Keep the Injector statically
If you are introducing DI into a lot of existing or legacy code, then it may be tempting to stash the Injector into a publicly-accessible object.
public class InjectorHolder() {
private InjectorHolder() {} // Not instantiable
private static Injector injector;
public static void initializeInjector() {
injector = Guice.createInjector(new AModule(), new BModule(), andSoOn());
}
public static Injector get() {
return injector;
}
public static B getB() {
return injector.getInstance(B.class);
}
}
At this point you can call InjectorHolder.get().getInstance(B.class) or InjectorHolder.getB() from the parts of the app you've migrated so far. Note that this may be difficult to test, and relies on Guice directly from across your application—both of which are not ideal.
Use Guice static injections
Guice provides a few features for static injection, notably the method call requestStaticInjection(Class... types). With a call to that in your module, Guice will inject static members that have #Inject annotations as soon as the Injector is created.
public class StaticBModule extends AbstractModule() {
#Override public void configure() { requestStaticInjection(BFactory.class); }
}
public class BFactory() {
#Inject #Named("B") private static Provider<B> bProvider;
public B get() {
return bProvider.get();
}
}
Now you can call new BFactory().get() instead of new B(), and it'll all go to the same injector. Naturally, you could also allow new B() instead if you put a static Provider<A> into your B class and request static injection for that instead, or you could keep your BFactory as an instance and replace it during tests to issue the B instances you need. At that point, you might as well just retrofit the classes that call new BFactory() to instead include a static Provider<B>, and have them inject statically, and then migrate those, all the way up until you have a full DI solution (explained below).
You may also consult this SO question, which has an example.
Ideal solution
You've shown us A and B, but presumably some other class C uses many instances of B, and maybe YourApplication (which contains your static main method) uses C. You can use Guice to create an instance of YourApplication or C, and then C can contain an injected Provider<B> bFactory. Then, rather than call new B(), you can call bFactory.get() to create as many B instances as you might need.
This way, your classes depend on exactly what they depend on, with no static state or references to Guice other than at the top level.

Related

Guice field injection

So here's the thing. I'm trying to inject some fields with guice, but it turns out that they are always null (not trying to use them on the constructor).
public class A {
#Inject
private SomeClass bar;
public A() {
foo();
}
public someMethod() {
bar.doSth();
}
}
public class B {
private A a;
public B() {
a = new A();
}
public someOtherMethod() {
a.someMethod();
}
}
Now whenever the app executed someOtherMethod and a tries to run bar.doSth a nice NullPointerException is raised.
So in order to fix this i ended Injecting the field manually inside the constructor:
public A() {
final Injector injector = Guice.createInjector();
bar = injector.getInstance(SomeClass.class);
}
But this is ugly, unclear, has a lot of boilerplate and I'm forced to do it on many places which make it tedious.
Is there any other way to archive this? Or an explanation of why the field is not being injected?
Thanks
Note:
I'm currently unavailable to do the propper injection on the constructor (with bar as a parameter) because of the refactoring it would imply. The project is now under heavy production and thus this kind of refactoring can't be done right now.
The IOC container only controls what you tell it to control. It doesn't know about the A inside of B, because it's being constructed directly, not managed by the container. You need to inject the A as well:
public class B {
#inject private A a;
public B() {}
...
}
And you can't just call new B() either, you need to inject the B as well.

What is actually involved in a mvp scenario to use google guice?

I am very familiar with using spring to inject using #Bean & #Autowired. I have switched over to looking at guice and I am wondering what is the minimum involved to have it functioning. The following basic example throws a NPE:
import javax.inject.Inject;
public class ClassA {
String a = "test";
#Inject
public ClassA() {
System.out.println(a);
}
public void go() {
System.out.println("two");
}
}
The following class attempting to instantiate a new instance of ClassA:
import javax.inject.Inject;
public class ClassB {
#Inject
ClassA guice;
public ClassB() {
guice.go();
}
public static void main(String[] args) {
ClassB b = new ClassB();
}
}
I have tried all sorts of combinations of the following with no success:
public class SupportModule extends AbstractModule {
#Override
protected void configure() {
bind(ClassA.class);
//bind(ClassA.class).to(ClassB.class);
//others too
}
}
I must be missing a key thing somewhere here, I'm not quite sure where? do I need some manual instantiation of guice/configuration itself? I assume I possibly do.
guice.go(); <= NullPointerException occurs here, obviously the obj is null because my guice setup isn't right
In Spring i can do the following, I assume Guice can aid me in doing this too:
#Bean
public FrameworkProperties properties() {
return new FrameworkProperties();
}
and then just:
#Autowired
FrameworkProperties props;
do I need some manual instantiation of guice/configuration itself? I assume I possibly do.
Yes, you assumed right. You'll have to bootstrap the Injector modules that you have defined using the Guice.createInjector() method. Also, one other thing to note is when using a custom defined constructor like in ClassB, you'll have to use constructor injection. So in order to get this working, ClassB should look like:
public class ClassB {
private ClassA guice;
#Inject //This will inject the dependencies used in the constructor arguments
public ClassB(final ClassA guice) {
this.guice = guice;
guice.go();
}
public static void main(String[] args) {
/**
* If only type to type binding is required, you can skip creating a Module class &
* bootstrap the injector with empty argument createInjector like used below. But, when
* there are other kind of bindings like Type to Implementations defined in modules, you can use:
* final Injector injector1 = Guice.createInjector(new GuiceModule1(), new GuiceModule2());
*/
final Injector injector = Guice.createInjector();
final ClassB b = injector.getInstance(ClassB.class); //This will create dependency graph for you and inject all dependencies used by ClassB and downwards
}
}
Also, you can remove the #Inject annotation used in ClassA's constructor as you are not injecting any external dependencies in that constructor. You can look up the Guice's getting started wiki for more documentation.

Creating Guice singleton that's not tied to an Injector

Our project is setup as follows:
1) Main module: Contains a driver program which starts a Spark streaming server. It has its own Guice injector.
2) When message comes in, it goes to another module, which creates it's own Guice injector.
3) This module uses classes in other modules which themselves use dependent modules. Each of these modules creates its own Guice injector so that it can work independently, tested individually etc.
Here's a problem: Now we need a Singleton, but an object created as #Singleton is bound to an injector (Not to a ClassLoader), so when the Injector goes away the object goes away.
Questions:
1) Is our architecture bad? Should we not be creating an injector in every module?
2) How do we create a Singleton that will remain in a ClassLoader even when injector goes away?
BTW, we use Netflix Governator on top on Guice.
Note: Answer for the question which is supposedly duplicate of this question doesn't answer how a 'single' injector created on the top level module can be passed to the sub-modules. Also, if the sub-modules themselves don't have an injector, can we write standalone unit tests for them?
An idea for question 2 would be to use a provider that you can bind in all your different Modules. This provider would access a singleton that that exists 'outside' of Guice.
I have crafted a simple example where I provide access to a static field. You can change that to use the implementation of the Singleton pattern that suits your needs.
public class SingletonProvider implements Provider<TheSingleton> {
private static final TheSingleton instance = new TheSingleton();
#Override
public TheSingleton get() {
return instance;
}
}
Then we bind this to our different modules
public class Module1 extends AbstractModule {
#Override
protected void configure() {
bind(TheSingleton.class).toProvider( SingletonProvider.class);
}
}
public class Module2 extends AbstractModule {
#Override
protected void configure() {
bind(TheSingleton.class).toProvider( SingletonProvider.class);
}
}
And then I create two different injectors that return this same instance
public class Test {
public static void main(String[] args) {
Injector injector1 = Guice.createInjector(new Module1());
TheSingleton instance = injector1.getInstance(TheSingleton.class);
System.out.println("instance = " + instance);
Injector injector2 = Guice.createInjector(new Module2());
TheSingleton instance2 = injector2.getInstance(TheSingleton.class);
System.out.println("instance2 = " + instance2);
}
}

Performance: Utility class vs. CDI bean

I want to externalize commonly used applicationlogic into a "utility class" called Helper. The applicationlogic needs other CDI beans to work.
Two possibilities:
a)
#SessionScoped
class ControllerWithCdiBean {
#Inject
Helper helper;
public void doIt() {
Object result = helpder.calculate();
}
}
#RequestScoped
class Helper{
#Inject
Service anyService;
public Object calculate() {
return anyService.calc();
}
}
b)
#SessionScoped
class ControllerWithStaticCallsViaDeltaspike {
public void doIt() {
Object result = Helpder.calculate();
}
}
class Helper{
private static Service anyService = BeanProvider.getContextualReference(Service.class);
public static Object calculate() {
return anyService.calc();
}
What about performance? Are there any notable differences? Both solutions are possible for me, is one solutions better than the other?
One disadvantage:
Helpder gets initialized for every Request.
Mark your Helper class as #ApplicationScoped. With this, you will have a single instance per application context.
Still, if it's just an utility class, it shouldn't be a managed bean at all. I would instead mark it as final, define a private constructor and mark all the methods as static. This is because since it's an utility class, it doesn't need to maintain any state.

Does Guice support a way of method injection (non setter injection)?

From what I understand Guice supports injection for: Constructors, Setters (which they call method injection for some reason), fields.
Can it also inject method parameters? For example:
void foo(InterfaceA a, InterfaceA a1){
...
}
interface InterfaceA{
...
}
class A implements InterfaceA{
....
}
class B implements InterfaceA{
....
}
I want to be able to bind a in foo to type A and a1 to B (will probably need annotation but lets ignore that for a second).
I want this to be done on invocation.
This seems different from the normal use cases (c'tor, fields, setters) in the sense that the dependency injection will happen on invocation rather than on object creation.
So is this possible?
Vladimir's answer is correct, but rather than injecting the injector, you can use field injection and Providers to do the same more concisely and to check that dependencies are satisfied at injector creation time. This code is the same as his, but modified to use Providers:
Injector injector = Guice.createInjector(b -> {
b.bind(InterfaceA.class).annotatedWith(Names.named("a")).to(A.class);
b.bind(InterfaceA.class).annotatedWith(Names.named("a1")).to(B.class);
b.bind(Invoke.class);
});
public class Invoke {
// Constructor injection works too, of course. These fields could also be
// made private, but this could make things difficult to test.
#Inject #Named("a") Provider<InterfaceA> aProvider;
#Inject #Named("a1") Provider<InterfaceA> a1Provider;
public void invoke() {
this.foo(aProvider.get(), a1Provider.get());
}
void foo(InterfaceA a, InterfaceA a1){
...
}
}
Well, you can do this:
Injector injector = Guice.createInjector(b -> {
b.bind(InterfaceA.class).annotatedWith(Names.named("a")).to(A.class);
b.bind(InterfaceA.class).annotatedWith(Names.named("a1")).to(B.class);
b.bind(Invoke.class);
});
public class Invoke {
private final Injector injector;
#Inject
Invoke(Injector injector) {
this.injector = injector;
}
public void invoke() {
this.foo(
injector.getInstance(Key.get(InterfaceA.class, Names.named("a"))),
injector.getInstance(Key.get(InterfaceA.class, Names.named("a1")))
);
}
void foo(InterfaceA a, InterfaceA a1){
...
}
}
But nothing more. Guice is a dependency injection framework and it usually means "construct objects with all their dependencies". While method parameters are dependencies formally (since the class is supposed to use them - this is the definition of dependency), they are not usually regarded as those by DI frameworks. It is understandable - this would make these frameworks much more complex for little to no gain, and also Java is not expressive enough language for such things not to look obscenely ugly.

Categories

Resources