在基于struts spring hibernate的开发框架下,一般service都是直接通过在Struts的action中getBean("yourServiceName")来获取,那么如果在serviceA中想调用serviceB中的方法该如何呢?
直接new 一个serviceB是不行的,因为里面可能还有依赖注入的dao等其他本来需要容器管理的资源,可以象在action中一样getBean()么?
获得applicationContext就可以了:
AppContext :


public class AppContext

{

** static ApplicationContext applicationContext;


public static ApplicationContext getApplicationContext()

{

return applicationContext;

}

public static void setApplicationContext(


ApplicationContext applicationContext)

{

AppContext.applicationContext = applicationContext;

}

}
SpringService:


public class SpringBeanService

{

** static SpringBeanService instance;

** 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)

{

}

}
感觉有点麻烦,有更简便的办法了么?
这篇文章大家可以参考一下,和本文有类似之处:
Struts调用Spring服务类的三种方法
引用:

3.朋友帮忙型 朋友多了好办事,凡事都自己动手总有一天会活活累死,所有Action为自己需要的Service提供setter,并且在Spring中注入,好累啊。小学生都在减负了,我们也来为Action减减负吧--提供一个专门

查找Serivice的ServiceLocator,负责获取所有的Service,该类为每个Service提供专门的获得方法,如: