Pengantar CDI (Injeksi Konteks dan Ketergantungan) di Java

1. Ikhtisar

CDI (Injeksi Konteks dan Ketergantungan) adalah kerangka kerja injeksi ketergantungan standar yang disertakan dalam Java EE 6 dan yang lebih tinggi.

Hal ini memungkinkan kita untuk mengelola siklus hidup komponen stateful melalui konteks siklus hidup spesifik domain dan memasukkan komponen (layanan) ke dalam objek klien dengan cara yang aman.

Dalam tutorial ini, kita akan melihat secara mendalam fitur-fitur CDI yang paling relevan dan menerapkan pendekatan berbeda untuk memasukkan dependensi di kelas klien.

2. DYDI (Do-it-Yourself Dependency Injection)

Singkatnya, dimungkinkan untuk mengimplementasikan DI tanpa menggunakan framework apa pun.

Pendekatan ini dikenal sebagai DYDI (Do-it-Yourself Dependency Injection).

Dengan DYDI, kami menjaga kode aplikasi tetap terisolasi dari pembuatan objek dengan meneruskan dependensi yang diperlukan ke dalam kelas klien melalui pabrik / pembangun lama biasa.

Berikut tampilan implementasi DYDI dasar:

public interface TextService { String doSomethingWithText(String text); String doSomethingElseWithText(String text); }
public class SpecializedTextService implements TextService { ... }
public class TextClass { private TextService textService; // constructor }
public class TextClassFactory { public TextClass getTextClass() { return new TextClass(new SpecializedTextService(); } }

Tentu saja, DYDI cocok untuk beberapa kasus penggunaan yang relatif sederhana.

Jika aplikasi sampel kami tumbuh dalam ukuran dan kompleksitas, mengimplementasikan jaringan yang lebih besar dari objek yang saling berhubungan, kami akan mencemari itu dengan banyak pabrik grafik objek.

Ini akan membutuhkan banyak kode boilerplate hanya untuk membuat grafik objek. Ini bukan solusi yang sepenuhnya dapat diskalakan.

Bisakah kita melakukan DI lebih baik? Tentu saja kita bisa. Di sinilah tepatnya CDI berperan.

3. Contoh Sederhana

CDI mengubah DI menjadi proses no-brainer, yang diringkas menjadi hanya menghias kelas layanan dengan beberapa anotasi sederhana, dan menentukan titik injeksi yang sesuai di kelas klien.

Untuk menunjukkan bagaimana CDI mengimplementasikan DI pada tingkat yang paling dasar, misalkan kita ingin mengembangkan aplikasi pengeditan file gambar sederhana. Mampu membuka, mengedit, menulis, menyimpan file gambar dan sebagainya.

3.1. The “beans.xml” Berkas

Pertama, kita harus menempatkan file "beans.xml" di folder "src / main / resources / META-INF /" . Meskipun file ini sama sekali tidak berisi arahan DI tertentu, itu diperlukan untuk mengaktifkan dan menjalankan CDI :

3.2. Kelas Layanan

Selanjutnya, mari buat kelas layanan yang menjalankan operasi file yang disebutkan di atas pada file GIF, JPG dan PNG:

public interface ImageFileEditor { String openFile(String fileName); String editFile(String fileName); String writeFile(String fileName); String saveFile(String fileName); }
public class GifFileEditor implements ImageFileEditor { @Override public String openFile(String fileName) { return "Opening GIF file " + fileName; } @Override public String editFile(String fileName) { return "Editing GIF file " + fileName; } @Override public String writeFile(String fileName) { return "Writing GIF file " + fileName; } @Override public String saveFile(String fileName) { return "Saving GIF file " + fileName; } }
public class JpgFileEditor implements ImageFileEditor { // JPG-specific implementations for openFile() / editFile() / writeFile() / saveFile() ... }
public class PngFileEditor implements ImageFileEditor { // PNG-specific implementations for openFile() / editFile() / writeFile() / saveFile() ... }

3.3. Kelas Klien

Terakhir, mari implementasikan kelas klien yang mengambil implementasi ImageFileEditor di konstruktor, dan mari kita tentukan titik injeksi dengan anotasi @Inject :

public class ImageFileProcessor { private ImageFileEditor imageFileEditor; @Inject public ImageFileProcessor(ImageFileEditor imageFileEditor) { this.imageFileEditor = imageFileEditor; } }

Sederhananya, anotasi @Inject adalah pekerja keras CDI yang sebenarnya. Ini memungkinkan kami untuk menentukan titik injeksi di kelas klien.

Dalam kasus ini, @Inject menginstruksikan CDI untuk memasukkan implementasi ImageFileEditor di konstruktor.

Furthermore, it's also possible to inject a service by using the @Inject annotation in fields (field injection) and setters (setter injection). We'll look at these options later.

3.4. Building the ImageFileProcessor Object Graph With Weld

Of course, we need to make sure that CDI will inject the right ImageFileEditor implementation into the ImageFileProcessor class constructor.

To do so, first, we should get an instance of the class.

As we won't rely on any Java EE application server for using CDI, we'll do this with Weld, the CDI reference implementation in Java SE:

public static void main(String[] args) { Weld weld = new Weld(); WeldContainer container = weld.initialize(); ImageFileProcessor imageFileProcessor = container.select(ImageFileProcessor.class).get(); System.out.println(imageFileProcessor.openFile("file1.png")); container.shutdown(); } 

Here, we're creating a WeldContainer object, then getting an ImageFileProcessor object, and finally calling its openFile() method.

As expected, if we run the application, CDI will complain loudly by throwing a DeploymentException:

Unsatisfied dependencies for type ImageFileEditor with qualifiers @Default at injection point...

We're getting this exception because CDI doesn't know what ImageFileEditor implementation to inject into the ImageFileProcessor constructor.

In CDI's terminology, this is known as an ambiguous injection exception.

3.5. The @Default and @Alternative Annotations

Solving this ambiguity is easy. CDI, by default, annotates all the implementations of an interface with the @Default annotation.

So, we should explicitly tell it which implementation should be injected into the client class:

@Alternative public class GifFileEditor implements ImageFileEditor { ... }
@Alternative public class JpgFileEditor implements ImageFileEditor { ... } 
public class PngFileEditor implements ImageFileEditor { ... }

In this case, we've annotated GifFileEditor and JpgFileEditor with the @Alternative annotation, so CDI now knows that PngFileEditor (annotated by default with the @Default annotation) is the implementation that we want to inject.

If we rerun the application, this time it'll be executed as expected:

Opening PNG file file1.png 

Furthermore, annotating PngFileEditor with the @Default annotation and keeping the other implementations as alternatives will produce the same above result.

This shows, in a nutshell, how we can very easily swap the run-time injection of implementations by simply switching the @Alternative annotations in the service classes.

4. Field Injection

CDI supports both field and setter injection out of the box.

Here's how to perform field injection (the rules for qualifying services with the @Default and @Alternative annotations remain the same):

@Inject private final ImageFileEditor imageFileEditor;

5. Setter Injection

Similarly, here's how to do setter injection:

@Inject public void setImageFileEditor(ImageFileEditor imageFileEditor) { ... }

6. The @Named Annotation

So far, we've learned how to define injection points in client classes and inject services with the @Inject, @Default , and @Alternative annotations, which cover most of the use cases.

Nevertheless, CDI also allows us to perform service injection with the @Named annotation.

This method provides a more semantic way of injecting services, by binding a meaningful name to an implementation:

@Named("GifFileEditor") public class GifFileEditor implements ImageFileEditor { ... } @Named("JpgFileEditor") public class JpgFileEditor implements ImageFileEditor { ... } @Named("PngFileEditor") public class PngFileEditor implements ImageFileEditor { ... }

Now, we should refactor the injection point in the ImageFileProcessor class to match a named implementation:

@Inject public ImageFileProcessor(@Named("PngFileEditor") ImageFileEditor imageFileEditor) { ... }

It's also possible to perform field and setter injection with named implementations, which looks very similar to using the @Default and @Alternative annotations:

@Inject private final @Named("PngFileEditor") ImageFileEditor imageFileEditor; @Inject public void setImageFileEditor(@Named("PngFileEditor") ImageFileEditor imageFileEditor) { ... }

7. The @Produces Annotation

Sometimes, a service requires some configuration to be fully-initialized before it gets injected to handle additional dependencies.

CDI provides support for these situations, through the @Produces annotation.

@Produces allows us to implement factory classes, whose responsibility is the creation of fully-initialized services.

To understand how the @Produces annotation works, let's refactor the ImageFileProcessor class, so it can take an additional TimeLogger service in the constructor.

The service will be used for logging the time at which a certain image file operation is performed:

@Inject public ImageFileProcessor(ImageFileEditor imageFileEditor, TimeLogger timeLogger) { ... } public String openFile(String fileName) { return imageFileEditor.openFile(fileName) + " at: " + timeLogger.getTime(); } // additional image file methods 

In this case, the TimeLogger class takes two additional services, SimpleDateFormat and Calendar:

public class TimeLogger { private SimpleDateFormat dateFormat; private Calendar calendar; // constructors public String getTime() { return dateFormat.format(calendar.getTime()); } }

How do we tell CDI where to look at for getting a fully-initialized TimeLogger object?

We just create a TimeLogger factory class and annotate its factory method with the @Produces annotation:

public class TimeLoggerFactory { @Produces public TimeLogger getTimeLogger() { return new TimeLogger(new SimpleDateFormat("HH:mm"), Calendar.getInstance()); } }

Whenever we get an ImageFileProcessor instance, CDI will scan the TimeLoggerFactory class, then call the getTimeLogger() method (as it's annotated with the @Produces annotation), and finally inject the Time Logger service.

If we run the refactored sample application with Weld, it'll output the following:

Opening PNG file file1.png at: 17:46

8. Custom Qualifiers

CDI supports the use of custom qualifiers for qualifying dependencies and solving ambiguous injection points.

Custom qualifiers are a very powerful feature. They not only bind a semantic name to a service, but they bind injection metadata too. Metadata such as the RetentionPolicy and the legal annotation targets (ElementType).

Let's see how to use custom qualifiers in our application:

@Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) public @interface GifFileEditorQualifier {} 
@Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) public @interface JpgFileEditorQualifier {} 
@Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER}) public @interface PngFileEditorQualifier {} 

Now, let's bind the custom qualifiers to the ImageFileEditor implementations:

@GifFileEditorQualifier public class GifFileEditor implements ImageFileEditor { ... } 
@JpgFileEditorQualifier public class JpgFileEditor implements ImageFileEditor { ... }
@PngFileEditorQualifier public class PngFileEditor implements ImageFileEditor { ... } 

Lastly, let's refactor the injection point in the ImageFileProcessor class:

@Inject public ImageFileProcessor(@PngFileEditorQualifier ImageFileEditor imageFileEditor, TimeLogger timeLogger) { ... } 

If we run our application once again, it should generate the same output shown above.

Custom qualifiers provide a neat semantic approach for binding names and annotation metadata to implementations.

In addition, custom qualifiers allow us to define more restrictive type-safe injection points (outperforming the functionality of the @Default and @Alternative annotations).

If only a subtype is qualified in a type hierarchy, then CDI will only inject the subtype, not the base type.

9. Conclusion

Tidak diragukan lagi, CDI membuat injeksi ketergantungan tidak perlu dipikirkan lagi , biaya penjelasan tambahan adalah usaha yang sangat kecil untuk mendapatkan injeksi ketergantungan yang terorganisir.

Ada kalanya DYDI masih memiliki tempatnya di atas CDI. Seperti saat mengembangkan aplikasi yang cukup sederhana yang hanya berisi grafik objek sederhana.

Seperti biasa, semua contoh kode yang ditampilkan dalam artikel ini tersedia di GitHub.