有这样一个需求,让工程启动的时候,就去调用某方法,工程是用S2SH的。
我想到了servlet ,然后init()去调用。但是这个方法里需要注入其他的XXXService,
在启到的时候就报错了。XXXService为空,原因是servlet 启动的顺序大于S2SH的启动
顺序,不知道还有什么方法。
我想到了servlet ,然后init()去调用。但是这个方法里需要注入其他的XXXService,
在启到的时候就报错了。XXXService为空,原因是servlet 启动的顺序大于S2SH的启动
顺序,不知道还有什么方法。
你的servlet中的service没人给他注入,当然报空了..
XXXService xxxService = (XXXService)webApplicationContext.getBean("XXXService");
象4楼所说的那样我感觉不行,一个项目中有两个容器用来管理同一个service 这个乱了。
你使用上边的代码不又创建了一个容器啊..
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。