sap服务器应用webservice加载spring的机制问题

本文介绍了解决SAP服务器中启动Webservice时无法获得Spring工厂中的类的问题。提供两种方法:一是通过编写ServicesSingleton类和InitServlet类实现;二是通过编写ContextUtil类并配置到Spring中实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      在项目开发中,使用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>

    第一种方法为开发项目使用的方法,第二种方法没有进行测试,有兴趣的可以试一下。

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值