Jax-ws 开发webService ,并使用spring注入service类

时间:2022-06-07 15:45:06

由于使用myeclipse自动生成的Delegate,所以在使用service实现层的时候,默认创建的时候都是使用new的方法;

这样就导致每一次请求过来都得new一个新的;如果service有注入其他的service时,就会出现null的情况;

出现该情况,有两种方法进行解决:

方法一,在serviceImpl实现成里面,使用的注入的service加一下null处理;

private ITestService testService;
private ITestService getTestService(){
  if(testervice==null){
    WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
    testService=(ITestService)context.getBean("testService");
  }
  return testService; }
public void setTestService(ITestService service) {
  this.testService = service;
}

方法二,添加Delegate类中添加注入(也可以在你创建的service加)

主要就3个地方:(代码标红的地方)

1、继承SpringBeanAutowiringSupport类;

2、Delegate实现类加注入@Controller;

3、在你需要注入的service加注入@Autowired

import javax.annotation.Resource;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.support.SpringBeanAutowiringSupport; @WebService(
  targetNamespace = "http://service.com/",
  serviceName = "AuthCodeService",
  portName = "service/AuthCodeServicePort",
  wsdlLocation = "WEB-INF/wsdl/AuthCodeService.wsdl")
@Controller
public class AuthCodeServiceDelegate extends SpringBeanAutowiringSupport implements IAuthCodeServiceDelegate {

   // 这个是默认创建的
// com.service.AuthCodeService authCodeService = new com.service.AuthCodeService(); @Autowired
private IAuthSmsService authSmsService; public Result SendSmsCode(
@WebParam(name="inaccessInfo") InaccessInfo inaccessInfo,
@WebParam(name="record") Record record
) {
inaccessInfo.setAccessSeq(inaccessInfo.getAccessSeq()+","+getClientInfo());
return authSmsService.sendSmsCode(inaccessInfo, record);
} @Resource
private WebServiceContext wsContext;
/**
* 获取请求端IP地址 --(这个是赠送的)
* <p>2017-4-14 上午10:15:08</p>
*/
private String getClientInfo(){
MessageContext mc = wsContext.getMessageContext();
HttpServletRequest request = (HttpServletRequest)(mc.get(MessageContext.SERVLET_REQUEST));
String remortAddress = request.getRemoteAddr();
return (remortAddress);
}
}

如发现其他方式,欢迎讨论~