在基於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 context
=contextEvent
getServletContext();

String path=context
getInitParameter(
setting
properties
);

InputStream in =context
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)

{

}

}
From:http://tw.wingwit.com/Article/program/Java/ky/201311/28919.html