春に豆を手に入れるには多くの方法があります。もう一度要約します。
最初のタイプ:初期化中にApplicationContextオブジェクトを保存します
applicationContext ac = new FilesystemxmlapplicationContext( "applicationContext.xml"); ac.getBean( "beanid");
注:この方法は、Spring Frameworkを使用したスタンドアロンアプリケーションに適しており、プログラムでは、プログラムが構成ファイルを介してSpringを手動で初期化する必要があります。
2番目のタイプ: Springが提供するツールクラスを介してApplicationContextオブジェクトを取得します
org.springframework.web.context.support.webapplicationcontextutils; applicationContext ac1 = webapplicationContextutils.getRequearedWebApplicationContext(servletcontext(servletcontext); applicationContext AC2 = webApplicationContextils.getWeBAppLicationContext(servetext) sc); ac1.getbean( "beanid"); ac2.getbean( "beanid");
説明:
1.これらの2つの方法は、Spring Frameworkを使用してB/Sシステムに適しており、ServletContextオブジェクトを介してApplicationContextオブジェクトを取得し、必要なクラスインスタンスを取得します。
2.最初のメソッドは、取得が失敗したときに例外をスローし、2番目のメソッドがnullを返します。
3番目のタイプ:抽象クラスApplicationObjectSupportから継承
注:抽象クラスApplicationObjectSupportによって提供されるgetApplicationContext()メソッドは、ApplicationContextインスタンスを簡単に取得し、スプリングコンテナでBeanを取得できます。 Springが初期化されると、ApplicationContextオブジェクトは、抽象クラスのSetApplicationContext(ApplicationContextコンテキスト)メソッドを介して注入されます。
4番目のタイプ:抽象クラスWebApplicationObjectSupportから継承
注:上記の方法と同様に、getWebApplicationContext();を呼び出して、WebApplicationContextインスタンスを取得します。
5番目のタイプ: Interface ApplicationContextAwareの実装
説明:このインターフェイスのSetApplicationContext(ApplicationContextコンテキスト)メソッドを実装し、ApplicationContextオブジェクトを保存します。 Springが初期化されると、ApplicationContextオブジェクトがこのメソッドを介して注入されます。
Springは、SpringのApplicationContextオブジェクトを取得するために、通常のクラスで対応するクラスまたはインターフェイスの継承または実装を実装する最後の3つの方法を提供しますが、使用する場合は、これらの抽象クラスまたはインターフェイスの継承または実装に注意する必要があります。または、取得したApplicationContextオブジェクトはnullになります。
以下は、インターフェイスApplicationContextAwareを実装して、スプリングコンテナで豆を入手する方法を示しています。
まず、ApplicationContextAwareインターフェイスを実装するクラスをカスタマイズし、内部のメソッドを実装します。
パッケージcom.ghj.tool; import org.springframework.beans.beansexception; Import org.springframework.context.applicationcontext; Import org.springframework.context.applicationcontextaware; private static springconfigtool springconfigtool = null; public synchronized static springconfigtool init(){if(springconfigtool == null){springconfigtool = new SpringConfigtool(); } springconfigtoolを返します。 } public void setApplicationContext(applicationContext applicationContext)throws beansexception {ac = applicationContext; } public synchronized static object getBean(string beanname){return ac.getbean(beanname); }}次に、ApplicationContext.xmlファイルで構成します。
次のようにコードをコピーします。<bean id = "springconfigtool"/>
最後に、次のコードを使用して、スプリングコンテナに対応する豆を入手できます。
コードコピーは次のとおりです。SpringConfigTool.getBean( "Beanid");
サーバーがスプリングコンテナの初期化を開始すると、次の方法でスプリングコンテナを取得できないことに注意してください。
org.springframework.web.context.contextloaderをインポートします。 org.springframework.web.context.webapplicationContextをインポートします。 webApplicationContext wac = contextloader.getCurrentWebApplicationContext(); wac.getbean(beanid);
上記はこの記事に関するものです。すべての人の学習に役立つことを願っています。