Use the CDI API framework in the Java class library for dependencies injection
Use the CDI API framework in the Java class library for dependencies injection
Dependent injection is a design pattern. Through this mode, we can entrust the dependency relationship between classes to manage external.Java provides a variety of ways to achieve dependency injection. One of them is to use CDI and Dependency Injection) API framework.
CDI is the standard for dependency injection and context management provided in the Java EE 6 specification.Its implementation can be used in Java SE or Java Ee applications.With the CDI API framework, we can easily manage and inject various dependencies.
The first step to achieve dependency injection is to use the annotation to identify the need to be injected in the code.In the CDI, there are two main annotations for the dependency injection point of the marking class: @Inject and @qualifier.
@Inject annotation is used to inject dependency items into the target class.It can be used on constructing functions, member variables or methods.For example, the following code demonstrates how to use @Inject to inject a dependencies called useService into the constructor in the UserService class::
public class UserService {
private final UserDAO userDAO;
@Inject
public UserService(UserDAO userDAO) {
this.userDAO = userDAO;
}
// Other methods...
}
@Qualifier annotation is used to identify different instances with the same type.It is usually used to distinguish multiple classes that implement the same interface.For example, the following code demonstrates how to use the @qualifier to mark a class named "MySQL" a class that implements the DataSource interface:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
public @interface MySqlDataSource {
}
Then, we can use @MysqldataSource annotations where you need to inject DataSource:
public class UserService {
@Inject
@MySqlDataSource
private DataSource dataSource;
// Other methods...
}
In addition to the basic @qualifier annotation, CDI also provides higher -level annotations, such as @named and @Default.@Named annotations can be used to inject dependencies according to the name, while @Default annotations can be used to specify the default dependencies.
To use the CDI API framework in the Java library for dependencies, we need to introduce the dependency item achieved by CDI.For example, in the Maven project, the following dependencies can be added:
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
<scope>provided</scope>
</dependency>
Then, the relevant class and annotations provided by the CDI API in the code for dependence in injection.
By using the CDI API framework, we can easily manage the dependencies in the application and improve the maintenance and testability of the code.It provides us with an elegant and flexible way to handle the dependence between classes.