1。春によって提供されるコンテキストローダー
webApplicationContext wac = contextloader.getCurrentWebApplicationContext(); wac.getBean(beanid);
この方法はサーブレットに依存せず、注入を必要としません。ただし、サーバーが起動し、スプリングコンテナが初期化されたときに、この方法でスプリングコンテナを取得できないことに注意する必要があります。
2。インターフェイスApplicationContextAwareを実装します
ツールクラスを定義します
Public Class SpringContextutilは、ApplicationContextAware {private static ApplicationContext ApplicationContext; //スプリングアプリケーションコンテキスト環境/** * ApplicationContextAwareインターフェイスのコールバックメソッドを実装し、コンテキスト環境 * @Param ApplicationContext * @Throws BeanSexception */public void setApplicationContext(ApplicationContext ApplicationContext)Throws BeanSexcection {SpringContextututil.Applicextext = ApplicationContext; } / ** * @return applicationContext * / public static applicationContext getApplicationContext(){return applicationContext; } / *** get object* @param name* @returnオブジェクト指定された名前で登録された豆のインスタンス* @throws beansexception* / public static object getbean(string name)throws beansexception {return applicationContext.getBean(name); } / ** * execlytypeのオブジェクトを取得 * beanをタイプで変換できない場合、対応する例外がスローされます(beannotofrequiredtypeexception) {return applicationContext.getBean(name、requiredType); } / ** * beanfactoryに指定された名前と一致するビーン定義が含まれている場合、true * @return boolean * / public static boolean containsbean(string name){return applicationContext.containsbean(name); } /***特定の名前に登録されているBean定義がSingletonまたはプロトタイプであるかどうかを判断します。 *指定された名前に対応するビーンの定義が見つからない場合、例外がスローされます(nosuchbeandefinitionexception) * @param name * @return boolean * @throws nosuchbeandefinitionexception */ public static boolean issingingleton(string name)Throws nosuchbeandefitionexception } / ** * @param name * @returnクラス登録オブジェクトのタイプ * @Throws nosuchbeandefinitionException * / public static class getType(string name)throws nosuchbeandefinitionexception {return applicationContext.getType(name); } / ** *与えられたBean名がBean定義にエイリアスがある場合、これらのエイリアスは返されます * @param name * @return * @throws nosuchbeandefinitionexception * / public static string [] getaliase(string name)throws nosuchbeandefinitionexception {return context.getAliases(name); }}3。豆を構成します
<! - springcontextutil codeを介してBeanを取得 - > <bean id = "springcontextutil"/>
要約します
上記は、スプリングがコードに豆を取得するいくつかの方法です。この記事の内容が、すべての人の勉強や仕事に役立つことを願っています。ご質問がある場合は、メッセージを残してコミュニケーションをとることができます。