有这样一个需求,让工程启动的时候,就去调用某方法,工程是用S2SH的。
我想到了servlet ,然后init()去调用。但是这个方法里需要注入其他的XXXService,
在启到的时候就报错了。XXXService为空,原因是servlet 启动的顺序大于S2SH的启动
顺序,不知道还有什么方法。

解决方案 »

  1.   

    用listener试试,就像listener启动定时器一样
      

  2.   

    在你的S2SH中,spring初始化应该是由Struts2中指定Objectfactory时候弄的,所以spring由Struts2启动..
    你的servlet中的service没人给他注入,当然报空了..
      

  3.   

    在init中通过spring获取serviceWebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
    XXXService xxxService = (XXXService)webApplicationContext.getBean("XXXService");
      

  4.   

    我想用这个做一个listener 但不知道怎么写,就是写出来后同样也需要注入一个service,
    象4楼所说的那样我感觉不行,一个项目中有两个容器用来管理同一个service 这个乱了。
      

  5.   

    是啊,本身项目在加载的时候就要创建一个容器,用来管理所有bean的创建和销毁,
    你使用上边的代码不又创建了一个容器啊..
      

  6.   

    这个不是新建,getRequiredWebApplicationContext(getServletContext());
      

  7.   

    你可以看spring的源代码:
    public static WebApplicationContext getWebApplicationContext(ServletContext sc) {
    return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    } /**
     * Find a custom WebApplicationContext for this web application.
     * @param sc ServletContext to find the web application context for
     * @param attrName the name of the ServletContext attribute to look for
     * @return the desired WebApplicationContext for this web app, or <code>null</code> if none
     */
    public static WebApplicationContext getWebApplicationContext(ServletContext sc, String attrName) {
    Assert.notNull(sc, "ServletContext must not be null");
    Object attr = sc.getAttribute(attrName);
    if (attr == null) {
    return null;
    }
    if (attr instanceof RuntimeException) {
    throw (RuntimeException) attr;
    }
    if (attr instanceof Error) {
    throw (Error) attr;
    }
    if (attr instanceof Exception) {
    IllegalStateException ex = new IllegalStateException();
    ex.initCause((Exception) attr);
    throw ex;
    }
    if (!(attr instanceof WebApplicationContext)) {
    throw new IllegalStateException("Context attribute is not of type WebApplicationContext: " + attr);
    }
    return (WebApplicationContext) attr;
    }
    注释上是这样写的:Find a custom WebApplicationContext for this web application.,还有这一句:Object attr = sc.getAttribute(attrName);是get,不是create。
      

  8.   

    你完全可以是ClassPathXml 这个类加载spring的xml文件去获取