前言:前面一文寫完了webservice的通信,然後接下來在實際項目中發現了webservice類中無法直接使用spring注解過的屬性,又經過将近一天的調查,腦子幾乎僵硬了,自己差點放棄,在上司的幫助下最終找到解決方案,就趕緊總結下來,人貴有思,好記憶不如爛筆頭,記錄下來就是資源。
首先,如果你是這樣直接使用的話,對象是空的,如下圖,moneyuserDAO是無法直接使用的,即使spring已經對其進行加載,但是在webservice中是不能直接使用的,但是spring加載的通路資料庫持久層的DAO對象等會存儲在WebApplicationContext中,那麼我有了以下的方式
第一步:寫好以下的單例内容
package com.ebiz.cms.webservice;
import org.springframework.web.context.WebApplicationContext;
public class ServicesSingleton {
private WebApplicationContext servletContext;
public WebApplicationContext getServletContext() {
return servletContext;
}
public void setServletContext(WebApplicationContext servletContext) {
this.servletContext = servletContext;
}
private volatile static ServicesSingleton singleton;
private ServicesSingleton() {
}
public static ServicesSingleton getInstance() {
if (singleton == null) {
synchronized (ServicesSingleton.class) {
if (singleton == null) {
singleton = new ServicesSingleton();
}
}
}
return singleton;
}
public Object getDAO(Class<?> classNameOfDAO) {
String implName = classNameOfDAO.getSimpleName();
String firstChar = implName.substring(0, 1);
implName = firstChar.toLowerCase() + implName.substring(1) + "Impl";
return singleton.getServletContext().getBeansOfType(classNameOfDAO).get(implName);
}
}
注意裡面最重要的getDAO方法和單例的實作方式,通過WebApplicationContext的getBeansOfType方法找到對應的DAO類。
第二步:編寫tomcat啟動時加載WebApplicationContext的類和xml配置
package com.ebiz.cms.webservice;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class InitServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -3962535683227715257L;
@Override
public void init() throws ServletException {
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
ServicesSingleton.getInstance().setServletContext(ctx);
}
}
<servlet>
<servlet-name>initServlet</servlet-name>
<servlet-class>com.ebiz.cms.webservice.InitServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
以上,就會将對應的WebApplicationContext對象加載到單例中,然後我們再在webservice對象中通過getDAO方法擷取對應的DAO對象對資料庫進行持久層操作
public String createMemPxy(String username, String password, String mobile, String email, String type) {
try {
ServicesSingleton single = ServicesSingleton.getInstance();
MembersDAO memberDAO = (MembersDAOImpl)single.getDAO(MembersDAO.class);
以上隻寫出service對象的service方法片段
總結:我在此過程中卡到了一個點就是,我沒有通過webservice之間的通路方式去擷取對象的單例,而是通過在service類中寫main方法去測試調用單例,卻發現在main方法中怎麼都不會擷取tomcat啟動時初始化好的單例,這是一個低級錯誤,因為經過一天的調查,腦子基本上以及僵硬了,不過經過上司的指點後,順利的解決了該問題。這樣,整體的Java調用webservice以及關聯spring的持久層操作就搞定了,舒心啊!