Thứ Hai, 10 tháng 9, 2018
Understanding Injection
Some definition first, until now I've used the term component when talking about the classes we've been developing. The term is not completely accurate. I should have used instead the term bean for our book repository. A bean is just an object that is managed by the Java EE runtime or container. With a broader view, we can say that in Java EE we have objects that are managed by containers. In fact, in Java EE every object is a bean. Well, I should say, most objects are beans. Most objects are beans except for JPA entities. The difference between a class and a bean is that the container gives a bean extra services such as lifecycle management, interception or injection. In terms of code, a bean is just a concrete Java class with a default constructor. Here the BookRepository class doesn't implement anyspecific interface nor it extends a specific class. It can have any annotation and can define any method. In fact, with very few exception, potentially every Java class with a default constructor is a bean in Java EE. So our BookRepository is considered a bean. But why should we care about knowing the difference between a simple class and a bean? Well because now we can use extra container services, one of them being injection. But what is injection? Applications are made of business logic, interaction with modules, user interface, external APIs and so on. In fact, in an object oriented programming language, like Java, all these can be summarized by objects depend on other objects or let's say beans depend on other beans. But instead of having beans creating their own dependencies, they can delegate these tasks to the container. This is what's called inversion of control. The control of choosing the dependency is inverted because it's given to an external container. The Java EE specification taking care of dependency injection is called CDI, or Context and Dependency Injection. CDI is built on the concept of loose coupling, strong typing. Meaning that beans are loosely coupled, but in a strongly typed way. The container's job is to inject references into these loosely coupled beans. CDI does much more than just injection and I would recommendattending the Pluralsight course dedicated to CDI. CDI decoupling goes further by bringing interceptors, decorators, events and context management to these beans. But that's not the purpose of this course. Let's see how to implement injection.
Đăng ký:
Đăng Nhận xét (Atom)
Không có nhận xét nào:
Đăng nhận xét