I can not understand the injection field

I am trying to understand dependecy injection.

I read a lot of articles, but the more I read, the more embarrassed.

So what I did is trying to understand some of the source code posted on the Google Guice page .

I realized that we need to create a module (ex: BillingModule ), where the binding between the interface and its implementation is performed:

 bind(BillingService.class).to(RealBillingService.class); 

And in the implementation class we have to inject constructor.

The problem is that I cannot understand the field injection :

 @Inject Connection connection; 

The question is simple: what does it mean?

+4
source share
2 answers

This means that you are not instantiating your object as usual:

 Connection connection = //someConstructor 

but you rather expect to receive it by other means. @Inject annotation defines the injection point, and exactly where you want your application server to instantiate the Connection object for you, depending on your configuration. Basically, this means that you are relieved of the difficulties of creating an instance of the Connection object and can only work with functionality.

Of course, if the application server does not support the insertion of the field or for some reason it failed, the @Inject annotation means nothing, and you get a null connection object.

+4
source

Indicates the members of your implementation class (constructors, methods, and fields) into which Injector must enter values. The injector performs injection requests for:

  • Every instance that he creates. A class under construction must have exactly one of its constructors, marked with @Inject or must have a constructor without parameters. Then the injector proceeds to execute the method and inject the field injections.

  • Finished instances are passed to injectMembers(Object) , toInstance(Object) and toProvider(Provider) . In this case, all constructors are, of course, ignored.

  • Static fields and class methods that any Module has a specially requested static injection for using requestStaticInjection(Class...) .

In all cases, a member can be entered regardless of its Java access specifier (private, default, secure, public).

+1
source

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


All Articles