程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Spring中的service之間如何調用

Spring中的service之間如何調用

編輯:關於JAVA

在基於struts+spring+hibernate的開發框架下,一般service都是直接通過在Struts的action中getBean("yourServiceName")來獲取,那麼如果在serviceA中想調用serviceB中的方法該如何呢?

直接new 一個serviceB是不行的,因為裡面可能還有依賴注入的dao等其他本來需要容器管理的資源,可以象在action中一樣getBean()麼?

獲得applicationContext就可以了:

AppContext : public class AppContext {
  private static ApplicationContext applicationContext;
  public static ApplicationContext getApplicationContext() {
    return applicationContext;
  }
  public static void setApplicationContext(
      ApplicationContext applicationContext) {
    AppContext.applicationContext = applicationContext;
  }
}

SpringService:

public class SpringBeanService {
  private static SpringBeanService instance;
  private ApplicationContext applicationContext;
  public static synchronized SpringBeanService getInstance() {
    if (instance == null) {
      instance = new SpringBeanService();
    }
    return instance;
  }
  public ApplicationContext getApplicationContext() {
    return this.applicationContext;
  }
  public void setApplicationContext(ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
  }
  public UserService getUserService(){
    return (UserService)AppContext.getApplicationContext().getBean("userService");
  }
  }

ApplicationContext的初始化:

public class ConfigLoadListener implements ServletContextListener {
  public void contextInitialized(ServletContextEvent contextEvent) {
    try {
      WebApplicationContext context =WebApplicationContextUtils.getRequiredWebApplicationContext(contextEvent.getServletContext());
      AppContext.setApplicationContext(context);
      //讀配置
      try {
        ServletContext context2=contextEvent.getServletContext();
        String path=context2.getInitParameter("setting.properties");
        InputStream in =context2.getResourceAsStream(path);
        Properties properties = new Properties();
        properties.load(in);
        GlobalConstant.setCmdbProperties(properties);
        in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } catch (HibernateException e) {
      System.out.println("系統無法初始化,異常退出");
      System.out.println(e);
    }
  }
  public void contextDestroyed(ServletContextEvent contextEvent) {
  }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved