web项目中简单的管理spring的上下文

在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注入了,就可以放心的使用了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值