在项目开发中,使用sap服务器进行系统开发。由于编写的是webservice,所以启动的时候要加载spring的类,而sap服务器在这时候就会出现无法获得spring工厂中的类,万分头疼。
解决方案就是最上方的webservice不要去依赖注入spring的类,而是要在方法中取获取该spring工厂中的类。
问题又出现了,spring工厂提供的类不能去new,只能通过其他途径去获取了。
有人说:好,写一个工厂类BeanFactory,内部使用ClassPathXmlApplicationContext类加载spring的配置文件,从而获得需要的类。
可是项目是web项目,如果再使用这样的加载机制就会出现spring工厂不单一的情况,获得的类也可能不是单一的。所以我们要从web方面处理。
解决方法有两种:
一、编写ServicesSingleton,代码如下:
public class ServicesSingleton {
private WebApplicationContext servletContext;
private static ServicesSingleton instance = null;
protected ServicesSingleton() {
}
public static ServicesSingleton getInstance() {
if (instance == null)
instance = new ServicesSingleton();
return instance;
}
public WebApplicationContext getServletContext() {
return servletContext;
}
public void setServletContext(WebApplicationContext servletContext) {
this.servletContext = servletContext;
}
}
然后编写初始化InitServlet,代码如下:
public class InitServlet extends HttpServlet {
@Override
public void init() throws ServletException {
WebApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext());
ServicesSingleton.getInstance().setServletContext(ctx);
}
}
上面的代码就是将spring工厂存放在ServicesSingleton的变量中。
最后编写web.xml把InitServlet添加进去,代码如下:
<servlet>
<servlet-name>initServlet</servlet-name>
<servlet-class>com.bris.otp.util.InitServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
这样就ok了。
二、编写ContextUtil,代码如下:
public class ContextUtil implements ApplicationContextAware {
// Spring应用上下文环境
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext appContext)
throws BeansException {
ContextUtil.applicationContext = appContext;
}
public static Object getBean(String beanId) throws BeansException {
return applicationContext.getBean(beanId);
}
}
填写spring配置文件,代码如下:
<bean id="contextUtil" class="com.bris.rmc.common.ContextUtil"></bean>
第一种方法为开发项目使用的方法,第二种方法没有进行测试,有兴趣的可以试一下。