Pengenalan CDI (Konteks dan Suntikan Ketergantungan) di Jawa

1. Gambaran keseluruhan

CDI (Contexts and Dependency Injection) adalah kerangka suntikan ketergantungan standard yang termasuk dalam Java EE 6 dan lebih tinggi.

Ini membolehkan kita menguruskan kitaran hidup komponen bernegara melalui konteks kitaran hidup khusus domain dan menyuntik komponen (perkhidmatan) ke objek pelanggan dengan cara yang selamat.

Dalam tutorial ini, kita akan melihat secara mendalam mengenai ciri-ciri CDI yang paling relevan dan menerapkan pendekatan yang berbeza untuk menyuntik kebergantungan di kelas pelanggan.

2. DYDI (Suntikan Ketergantungan Sendiri)

Ringkasnya, adalah mungkin untuk melaksanakan DI tanpa menggunakan kerangka kerja sama sekali.

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

Dengan DYDI, kami membiarkan kod aplikasi diasingkan dari penciptaan objek dengan meneruskan kebergantungan yang diperlukan ke kelas pelanggan melalui kilang / pembangun lama biasa.

Beginilah rupa pelaksanaan DYDI asas:

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(); } }

Sudah tentu, DYDI sesuai untuk beberapa kes penggunaan yang agak mudah.

Sekiranya aplikasi sampel kami bertambah dari segi ukuran dan kerumitan, dengan menerapkan rangkaian objek yang saling berkaitan, kami akan mencemarkannya dengan banyak kilang grafik objek.

Ini memerlukan banyak kod pelat boiler hanya untuk membuat grafik objek. Ini bukan penyelesaian sepenuhnya.

Bolehkah kita melakukan DI lebih baik? Sudah tentu, kita boleh. Di sinilah sebenarnya CDI masuk ke dalam gambar.

3. Contoh Mudah

CDI mengubah DI menjadi proses yang tidak perlu, hanya untuk menghiasi kelas perkhidmatan dengan beberapa anotasi sederhana, dan menentukan titik suntikan yang sesuai di kelas pelanggan.

Untuk menunjukkan bagaimana CDI menerapkan DI pada tahap paling asas, anggaplah bahawa kita ingin mengembangkan aplikasi penyuntingan fail gambar yang sederhana. Mampu membuka, menyunting, menulis, menyimpan fail gambar dan sebagainya.

3.1. The "beans.xml" Fail

Pertama, kita mesti meletakkan fail "beans.xml" dalam folder "src / main / resources / META-INF /" . Walaupun fail ini sama sekali tidak mengandungi arahan DI tertentu, ia diperlukan untuk menghidupkan dan menjalankan CDI :

3.2. Kelas Perkhidmatan

Seterusnya, mari buat kelas perkhidmatan yang melakukan operasi fail yang disebutkan di atas pada fail 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 Pelanggan

Akhirnya, mari kita laksanakan kelas pelanggan yang mengambil pelaksanaan ImageFileEditor di konstruktor, dan mari kita tentukan titik suntikan dengan anotasi @Inject :

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

Ringkasnya, anotasi @Inject adalah tenaga kerja sebenar CDI. Ini membolehkan kita menentukan titik suntikan di kelas pelanggan.

Dalam kes ini, @Inject memerintahkan CDI untuk menyuntik pelaksanaan ImageFileEditor dalam konstruktor.

Selain itu, anda juga boleh menyuntik perkhidmatan dengan menggunakan anotasi @Inject di bidang (suntikan bidang) dan setter (setter injection). Kami akan melihat pilihan ini kemudian.

3.4. Membina Graf Objek ObjekFileProcessor Dengan Kimpalan

Sudah tentu, kita perlu memastikan bahawa CDI akan menyuntikkan pelaksanaan ImageFileEditor yang betul ke dalam konstruktor kelas ImageFileProcessor .

Untuk melakukannya, pertama, kita harus mendapat contoh kelas.

Oleh kerana kami tidak akan bergantung pada pelayan aplikasi Java EE untuk menggunakan CDI, kami akan melakukan ini dengan Weld, pelaksanaan rujukan CDI di 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(); } 

Di sini, kami membuat objek WeldContainer , kemudian mendapatkan objek ImageFileProcessor , dan akhirnya memanggil kaedah openFile () .

Seperti yang diharapkan, jika kita menjalankan aplikasi, CDI akan mengeluh keras dengan melemparkan DeploymentException:

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

Kami mendapat pengecualian ini kerana CDI tidak tahu apa pelaksanaan ImageFileEditor untuk disuntik ke dalam konstruktor ImageFileProcessor .

Dalam terminologi CDI , ini dikenali sebagai pengecualian suntikan yang tidak jelas .

3.5. The @Default dan @Alternative Anotasi

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 menjadikan suntikan kebergantungan tidak perlu dipertimbangkan , kos anotasi tambahan adalah sedikit usaha untuk mendapatkan suntikan kebergantungan yang teratur.

Ada kalanya DYDI masih mempunyai tempat berbanding CDI. Seperti ketika mengembangkan aplikasi yang cukup sederhana yang hanya mengandungi grafik objek sederhana.

Seperti biasa, semua contoh kod yang ditunjukkan dalam artikel ini terdapat di GitHub.