Spring框架中Servlet的单例问题

本文探讨了Spring框架中SpringBean默认采用的单例模式,并通过测试代码示例,展示了在不同请求间成员变量如何保持独立,避免线程安全问题。文章推荐了获取HttpServletRequest对象的安全方式,包括Controller方法入参形式和使用特定Util类。

精选30+云产品,助力企业轻松上云!>>> hot3.png

测试代码(Spring Bean默认使用单例模式)
    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;

    @GetMapping("/test")
    @ResponseBody
    public void test() throws IOException {
//        return request.getParameter("a");
        response.getWriter().println("hello");
        response.getWriter().flush();
    }

    @GetMapping("/test2")
    @ResponseBody
    public void test2() throws InterruptedException {
        TimeUnit.SECONDS.sleep(5);
//        int i = 0;
//        while (i < 20) {
//            TimeUnit.SECONDS.sleep(5);
//            System.out.println(request.getParameter("a"));
//            i++;
//        }
//        return request.getParameter("a");
    }
结论

成员变量注入的方式不会出现线程安全问题,主要原因是ThreadLocal将线程间的变量进行隔离。获取HttpServletRequest对象的建议使用方式:

  • Controller方法入参形式获取;
  • 使用以下Util获取:
public final class SpringServletUtil {

    public static HttpServletRequest getHttpServletRequest() {
        return getServletRequestAttributes().getRequest();
    }

    public static HttpServletResponse getHttpServletResponse() {
        return getServletRequestAttributes().getResponse();
    }

    public static HttpSession getHttpSession(boolean create) {
        return getHttpServletRequest().getSession(create);
    }

    public static HttpSession getHttpSession() {
        return getHttpSession(true);
    }

    public static ServletContext getServletContext() {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        if (webApplicationContext == null) {
            return null;
        }
        return webApplicationContext.getServletContext();
    }


    private static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    }


    private SpringServletUtil() {
    }
}
参考资料
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值