1. Use @ Inject to Inject the component parameters and variable Fields
You can inject variable fields, component parameters, and setter methods (or any real method)
The following is an example of incremental domain injection:
Example 1. Use AutomatedTellerMachineImpl. transport to add @ Inject to the variable domain transport
...
Public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {
@ Inject
Private ATM transport;
Example 2: Use AutomatedTellerMachineImpl. transport to add @ Inject Parameters
...
Public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {
@ Inject
Public AutomatedTellerMachineImpl (ATM transport ){
This. transport = transport;
}
This kind of flexibility allows you to easily create a single-Element Test class.
2. Use a simple ticket @ Produces
If the object you create can be complex, you can use a factory to create an instance, instead of relying on the builder. In CDI, you can use @ Produces in your factory class. For example:
The following is an example of incremental domain injection:
Example 3. TransportFactory. createTransport use @ Produces to define a factory Method
Package org. cdi. advocacy;
Import javax. enterprise. inject. Produces;
Public class TransportFactory {
@ Produces ATM transport createTransport (){
System. out. println ("ATM transport created with producer ");
Return new StandardAtmTransport ();
}
}
The factory method can enable the use of restricted words as a class description. In this example, we didn't use a limit. AutomatedTellerMachineImpl does not need to specify any specific restricted words. The following example uses the AutomatedTellerMachineImpl command to receive a simple single producer.
Example 4: Use AutomatedTellerMachineImpl. transport to add @ Inject Parameters
Import javax. inject. Inject;
Import javax. inject. Named;
@ Named ("atm ")
Public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {
@ Inject
Private ATM transport;
...
Run the ATM main to check whether the output is correct.
Output