Home > OS >  What is @Inject for in Kotlin?
What is @Inject for in Kotlin?

Time:11-14

I've read what the annotation says but I'm kinda dumb, so couldn't understand propertly

Identifies injectable constructors, methods, and fields. May apply to static as well as instance members. An injectable member may have any access modifier (private, package-private, protected, public). Constructors are injected first, followed by fields, and then methods. Fields and methods in superclasses are injected before those in subclasses. Ordering of injection among fields and among methods in the same class is not specified.

Can you explain me what is @Inject for? If it is possible with a real life analogy with something less abstract

CodePudding user response:

@Inject is a Java annotation for describing the dependencies of a class that is part of Java EE (now called Jakarta EE). It is part of CDI (Contexts and Dependency Injection) which is a standard dependency injection framework included in Java EE 6 and higher.

The most notorious feature of CDI is that it allows you to inject dependencies in client classes. What do I mean by dependencies? It is basically what your class needs to do whatever it needs to do.

Let me give you an example so that it is easier to understand. Imagine that you have a class NotificationService that is supposed to send notifications to people in different formats (in this case, email and sms). For this, you would most probably like to delegate the actual act of sending the notifications to specialized classes capable of handling each format (let's assume EmailSender and SmsSender). What @Inject allows you to do is to define injection points in the NotificationService class. In the example below, @Inject instructs CDI to inject an EmailSender and SmsSender implementation objects via the constructor.

public class NotificationService {
    
    private EmailSender emailSender;
    private SmsSender smsSender;
    
    @Inject
    public NotificationService(EmailSender emailSender, SmsSender smsSender) {
        this.emailSender = emailSender;
        this.smsSender = smsSender;
    }
}

It is also possible to inject an instance of a class in fields (field injection) and setters (setter injection), not only as depicted above in constructors.

One of the most famous JVM frameworks taking advantage of this dependency injection concept is Spring.

  • Related