public class ServiceLocator
{
private static ApplicationContext applicationContext; //Spring应用上下文环境
//下面的这个方法上加了@Override注解,原因是继承ApplicationContextAware接口是必须实现的方法
public static ApplicationContext getContext()
{
return applicationContext;
}
public static Object getBean(String name)
{
return applicationContext.getBean(name);
}
public static void setApplicationContext(ApplicationContext applicationContext){
ServiceLocator.applicationContext = applicationContext;
}
}
public class StartupServlet extends HttpServlet {
/**
* 描述
*/
private static final long serialVersionUID = 6871531526585981445L;
public void init() throws ServletException {
//将applicationContext放入ServiceLocator
ApplicationContext ctx = WebApplicationContextUtils
.getRequiredWebApplicationContext(this.getServletContext());
ServiceLocator.setApplicationContext(ctx);
}
}
本文介绍了一个基于Spring框架的Service Locator模式实现,通过该模式可以方便地获取Spring容器中的bean实例。文章提供了ServiceLocator类和StartupServlet类的具体实现,展示了如何初始化Spring应用上下文并将其注入到ServiceLocator中。
173万+

被折叠的 条评论
为什么被折叠?



