Exploring Contexts and dependency injection

CDI is Java EE's attempt at bringing DI into Java EE. While not as fully-fledged as Spring, CDI aims to standardize the basics of how DI is done. Spring supports the standard annotations defined in JSR-330. For the most part, these annotations are treated the same way as Spring annotations.

Before we can use CDI, we will need to ensure that we have dependencies for CDI jars included. Here's the code snippet:

    <dependency> 
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>

In this table, let's compare the CDI annotations with the annotations provided by Spring Framework. It should be noted that @Value, @Required, and @Lazy Spring annotations have no equivalent CDI annotations.

CDI annotation

Comparison with Spring annotations

@Inject

Similar to @Autowired. One insignificant difference is the absence of the required attribute on @Inject.

@Named

@Named is similar to @Component. Identifies named components. In addition, @Named can be used to qualify the bean with a name similar to the @Qualifier Spring annotation. This is useful in situations when multiple candidates are available for the autowiring of one dependency.

@Singleton

Similar to the Spring annotation @Scope("singleton").

@Qualifier

Similar to a similarly named annotation in Spring--@Qualifier

..................Content has been hidden....................

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