——————————————————————————–
原文鏈接:https://code.google.com/p/jee6-cdi/wiki/DependencyInjectionAnIntroductoryTutorial
本部分講述@Producer。
1. 使用@Producer來決定如何創建
可能你希望從AutomatedTellerMachineImpl中把選取傳輸器的方法分離出來。
你可以創建一個Producer方法來決定創建和選取傳輸器,看下面的實例:
例 1. TransportFactory決定使用/創建哪個傳輸器
package org.cdi.advocacy;
import javax.enterprise.inject.Produces;
public class TransportFactory {
private boolean useJSON = true;
private boolean behindFireWall = true;
@Produces ATMTransport createTransport() {
//Look up config parameters in some config file or LDAP server or database
System.out.println(“ATMTransport created with producer makes decisions”);
if (behindFireWall) {
if (useJSON) {
System.out.println(“Created JSON transport”);
return new JsonRestAtmTransport();
} else {
System.out.println(“Created SOAP transport”);
return new SoapAtmTransport();
}
} else {
System.out.println(“Created Standard transport”);
return new StandardAtmTransport();
}
}
}
把創建動作從AutomatedTellerMachineImpl代碼中分離出來是比較高級的做法。
可能你不總是這麼做,但是如果是的話,producer可以幫助你。
輸出和前面的一樣。
Output
ATMTransport created with producer makes decisions
Created JSON transport
deposit called
communicating with bank via JSON REST transport
2. 在@Producer中使用限定詞來決定如何創建
這個例子在最後構建
你同樣可以吧註入項作為參數傳入到producer中,如下:
例 2. TransportFactory決定使用/創建哪個傳輸器
package org.cdi.advocacy;
import javax.enterprise.inject.Produces;
public class TransportFactory {
private boolean useJSON = true;
private boolean behindFireWall = true;
@Produces ATMTransport createTransport( @Soap ATMTransport soapTransport,
@Json ATMTransport jsonTransport) {
//Look up config parameters in some config file
System.out.println(“ATMTransport created with producer makes decisions”);
if (behindFireWall) {
if (useJSON) {
System.out.println(“return passed JSON transport”);
return jsonTransport;
} else {
System.out.println(“return passed SOAP transport”);
return soapTransport;
}
&nb