Contexts and Dependency Injection Framework
Learn how to replace Spring annotations with CDI annotations.
We'll cover the following
Contexts and Dependency Injection (CDI) is an interface that standardizes dependency injection for Java EE. It defines different annotations for dependency injection like @Named
, @Inject
, @Scope
, @Singleton
, etc. Different CDI implementation frameworks provide support and functionality for these annotations.
@Named
is used to define a bean and @Inject
is used for autowiring one bean into another. Spring supports most of the annotations defined by CDI.
For the code example shown in this lesson, we have created a sub-package called lesson12
inside the package io.datajek.spring.basics.movierecommendersystem
.
The package contains MovieRecommenderSystemApplication.java
, Filter.java
, ContentBasedFilter.java
, CollaborativeFilter.java
, and RecommenderImplementation.java
files.
To be able to use CDI annotations in our Spring application, we need to add a dependency in the pom.xml
file as follows:
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
The dependency is automatically downloaded when the pom.xml
file is saved and is visible in the Maven Dependencies
folder as javax.inject-1.jar
. This jar lists the annotations defined by CDI. Now, we can use these annotations in our application.
@Named
Spring framework provides an implementation for some CDI annotations. In Spring framework, a bean is declared using the @Component
annotation. However, it also supports the @Named
annotation. This means we can replace the @Component
from the RecommenderImplementation
, ContentBasedFilter
, and CollaborativeFilter
classes and use @Named
to declare components.
Let’s have a look at the annotation replacement in the RecommenderImplementation
class first:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.