在web项目中,并不是所有请求的service都是通过ioc注入到action或其他地方
如果想要单独从spring中获取bean,那么简单的方式就是从spring上下文中获取。
以下是代码:
1.上下文管理类:
package littlehow.listener; import org.springframework.context.ApplicationContext; /** * SpringContext * * @author littlehow * @time 2016-06-20 16:20 */ public class SpringContext { private static ApplicationContext ctx = null; private static boolean init = false; /** * 初始化上下文 * @param _ctx */ public static synchronized void setCtx (ApplicationContext _ctx) { if (!init) { ctx = _ctx; init = true; } } /** * 获取值 * @param beanName * @return */ public static Object getBean(String beanName) { return ctx.getBean(beanName); } }
2.监听
package littlehow.listener; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import org.springframework.context.ApplicationContext; import org.springframework.web.context.ContextLoaderListener; import org.springframework.web.context.support.WebApplicationContextUtils; /** * SpringListener * * @author littlehow * @time 2016-06-20 16:24 */ public class SpringListener extends ContextLoaderListener { public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); /** 获取spring上下文 */ ServletContext context = event.getServletContext(); ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context); SpringContext.setCtx(ctx); } }
只有web.xml配置了,该监听才能生效,配置如下:
<listener>
<listener-class>littlehow.listener.SpringListener
</listener-class>
</listener>
那么再容器启动时,会加载spring监听,super.contextInitialized会初始化spring上下文。
最后在其他地方就可以通过getBean来获取spring的对象实例,根据beanid获取即可。
这时候类直接的依赖关系,spring都通过ioc注入了,就可以放心的使用了。