java

位置:IT落伍者 >> java >> 浏览文章

Spring中的service之间如何调用


发布日期:2021年10月09日
 
Spring中的service之间如何调用
在基于struts+spring+hibernate的开发框架下一般service都是直接通过在Struts的action中getBean(yourServiceName)来获取那么如果在serviceA中想调用serviceB中的方法该如何呢?

直接new 一个serviceB是不行的因为里面可能还有依赖注入的dao等其他本来需要容器管理的资源可以象在action中一样getBean()么?

获得applicationContext就可以了

AppContext

publicclassAppContext{

privatestaticApplicationContextapplicationContext;

publicstaticApplicationContextgetApplicationContext(){

returnapplicationContext;

}

publicstaticvoidsetApplicationContext(

ApplicationContextapplicationContext){

AppContextapplicationContext=applicationContext;

}

}

SpringService

publicclassSpringBeanService{

privatestaticSpringBeanServiceinstance;

privateApplicationContextapplicationContext;

publicstaticsynchronizedSpringBeanServicegetInstance(){

if(instance==null){

instance=newSpringBeanService();

}

returninstance;

}

publicApplicationContextgetApplicationContext(){

returnthisapplicationContext;

}

publicvoidsetApplicationContext(ApplicationContextapplicationContext){

thisapplicationContext=applicationContext;

}

publicUserServicegetUserService(){

return(UserService)AppContextgetApplicationContext()getBean(userService);

}

}

ApplicationContext的初始化

publicclassConfigLoadListenerimplementsServletContextListener{

publicvoidcontextInitialized(ServletContextEventcontextEvent){

try{

WebApplicationContextcontext=WebApplicationContextUtilsgetRequiredWebApplicationContext(contextEventgetServletContext());

AppContextsetApplicationContext(context);

//读配置

try{

ServletContextcontext=contextEventgetServletContext();

Stringpath=contextgetInitParameter(settingproperties);

InputStreamin=contextgetResourceAsStream(path);

Propertiesproperties=newProperties();

propertiesload(in);

GlobalConstantsetCmdbProperties(properties);

inclose();

}catch(IOExceptione){

eprintStackTrace();

}

}catch(HibernateExceptione){

Systemoutprintln(系统无法初始化异常退出);

Systemoutprintln(e);

}

}

publicvoidcontextDestroyed(ServletContextEventcontextEvent){

}

}

上一篇:如何在struts中应用国际化

下一篇:Struts 配置与组件介绍