2025-05-23


——————————————————————————–


原​文​鏈​接​: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

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *