Dependency injection and JSR-330

Before diving into Guice injection, let's look at the DI pattern again, along with JSR-330, in brief. 

A dependency injection mechanism enables an object to pass dependencies to another object. In Java, using DI, we can move dependency resolution from compile time to runtime. DI removes hard dependency between two Java classes; this allows us to reuse class as much as and also classes are  independently testable.

Java Specification Request-330: There is a different way to define dependency in Java classes, but @Inject and @Named are the most common annotations used to describe dependencies in Java classes from JSR-330. According to JSR-330, objects can be injected into the class constructor, the parameter of the method, and a field level. As per best practices, static field and method-level injection should be avoided for the following reasons:

  • Static field only injected when the first-time class object was created via DI, which makes static field inaccessible for the constructor
  • At runtime, the compiler complains if a static field is marked as final
  • When the first instance of the class is created, only static methods are called

As per JSR-330, the injection can be performed in this order: first, constructor injection; then field injection; and the last is method level injection. But, you can't expect the methods or fields to be called in the sequence of their assertion in the class.

A constructor can't use injected member variables, because field and method parameter injection takes place only after calling a constructor.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.133.233