在基于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){
}
}