国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

直接召喚系與IoCfashion使用Spring

2019-11-18 11:37:38
字體:
來源:轉載
供稿:網友

   SPRing再強大,也要面對降臨的問題--因為Spring不是Weblogic、Tomcat般的頂層容器,Servlet和EJB對象不由它創建,所以它必須要降臨到Weblogic、Tomcat所在的位面。
     初學者一般不用管那么多,照著Spring+hibernate+Struts之類的Sample就做了,但慢慢的,也許就要開始在jsp+javabean體系,土制框架,Singleton類等環境下使用Spring了。
     《Professional Java Development with the Spring Framework》第3章有"Managing the Containe"一節講這個問題。一般可以分為直接召喚系與IoC fashion兩類。


     1.直接召喚系--Singleton的application Context
      最簡單的,就像在UnitTest里那樣,直接構造Application Context:


ApplicationContext ctx = new ClasspathxmlApplicationContext("ApplicationContext.xml");
   
      在Web環境里,會使用ContextLoader構造ApplicationContext后,壓進Servlet Context。
      由ContextLoaderListener或ContextLoaderServlet,在Web應用啟動時完成。
      然后在Jsp/Servelet中,可以通過Servlet Context取得ApplicationContext: ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application);
    
      但像Singleton類或者EJB中,就沒有Servlet Context可用了。
      假如全部像UnitTest那樣直接構造,速度就會很不堪。自然的,就想到把ApplicationContext做成單例。
      Spring提供了ContextSingletonBeanFactoryLocator這樣的物體。
      先搞一個beanRefFactory.xml,里面寫上所有的applcationContext-*.xml文件名,并把Context命名為"default-context": <beans>
  <bean id="default-context"  class="org.springframework.context.support.ClassPathXmlApplicationContext">
    <constrUCtor-arg>
      <list> <value>applicationContext.xml</value></list>
    </constructor-arg>
  </bean>
</beans>
  然后讓loactor去找它,但代碼有點長: BeanFactoryReference bfr =  DefaultLocatorFactory.getInstance().useBeanFactory("default-context");
BeanFactory factory = bfr.getFactory();
MyService myService = factory.getBean("myService");
bfr.release();
// now use myService


    上面的代碼實在是太靈活,太麻煩了。
    還不如自己實現一個簡單的Singleton,擴展ContextLoaderListener類,在Web系統啟動時壓入Singleton。


    新的ContextLoaderListener類重載如下,ContextUtil中包含一個靜態的ApplicationContext變量:
    public void contextInitialized(ServletContextEvent event)
    {
        super.contextInitialized(event);


        ServletContext context = event.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        ContextUtil.setContext(ctx);
    }
   用家可直接取用:
 ApplicationContext context = ContextUtil.getContext();




發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 安达市| 达尔| 连山| 辽阳市| 和顺县| 清徐县| 静乐县| 丹寨县| 富平县| 保山市| 红安县| 庆元县| 湄潭县| 塔城市| 营山县| 合肥市| 黔西县| 大名县| 沈丘县| 鹰潭市| 称多县| 建湖县| 呼图壁县| 乌拉特前旗| 福贡县| 邮箱| 伊金霍洛旗| 仁寿县| 灵石县| 浠水县| 岳池县| 望城县| 乌拉特前旗| 汾西县| 临泽县| 谷城县| 苏尼特右旗| 新营市| 赤壁市| 大新县| 绥德县|