Geek injection injector or general provider somehow

I need to have lazyload logic to create mappers in my class. Each resolver is inherited from the Mapper<T> interface. But after the operation time of the object, he can use several cards depending on the input that he processes.

As I see it, this is not a good way to inject an injector into a class, but how can I implement lazyload, am not doing this? I cannot use the Provider<Mapper> because the provider has no options to determine which exact mapmaker I need at the moment.

Many thanks.

+4
source share
1 answer

This may not be the best solution, but it may work for you.

You can implement a provider that allows you to provide dynamic input. Then ask the provider to enter the classes they need so that you can create your object that you need dynamically.

Here is a snippet from the Provider JavaDoc :

A provider instance can always be selected in the implementation class, instead of directly entering T. This can give you access to multiple instances, instances that you want to mutate and discard safely, instances that are not available (for example, using @RequestScoped object from @SessionScoped object) or instances that will be initialized lazily.

It may look something like this: I personally think that it is normal to inject an injector into a provider, because it is part of the injection framework. The goal is to leave the Injector outside of your application code, and that certainly does.

 public class FooProvider implements Provider<Foo> @Inject private Injector injector; private String input; public void setInput(String input){ this.input = input; } @Override public Foo get(){ if(input.equals("bar")){ injector.getInstance(Bar.class); // Bar implements Foo } else{ injector.getInstance(Baz.class; // Baz implements Foo } } } 

Then in another place ...

 public class Goo{ @Inject Provider<Foo> fooProvider; public Foo goo(String input){ fooProvider.setInput(input); return fooProvider.get(); } } 

The key is to make sure that each provider instance is unique for each injection point, which, in my opinion, is the default. Since this provider has a mutable state, you cannot force it to be thrown around your application (and possibly do the wrong thing in a multi-threaded environment) if that is not what you intend to do. Then you will need to take extra precautions.

+3
source

Source: https://habr.com/ru/post/1413183/


All Articles