熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java開源技術 >> 正文

Spring中的service之間如何調用

2022-06-13   來源: 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) {
        AppContextapplicationContext = 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 thisapplicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        thisapplicationContext = applicationContext;
    }

    public UserService getUserService(){
        return (UserService)AppContextgetApplicationContext()getBean(userService);
    }
    
    }

  ApplicationContext的初始化


public class ConfigLoadListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent contextEvent) {  
        try {
            WebApplicationContext context =WebApplicationContextUtilsgetRequiredWebApplicationContext(contextEventgetServletContext());
            AppContextsetApplicationContext(context);

            //讀配置
            try {
                ServletContext context=contextEventgetServletContext();
                String path=contextgetInitParameter(settingproperties);
                InputStream in =contextgetResourceAsStream(path);
                Properties properties = new Properties();
                propertiesload(in);
                GlobalConstantsetCmdbProperties(properties);
                inclose();
            } catch (IOException e) {
                eprintStackTrace();
            }
        } catch (HibernateException e) {
            Systemoutprintln(系統無法初始化異常退出);
            Systemoutprintln(e);
        }
    }
   
    public void contextDestroyed(ServletContextEvent contextEvent) {
    }
}
From:http://tw.wingwit.com/Article/program/Java/ky/201311/28919.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.