温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring MVC Controller单例陷阱是什么

发布时间:2021-10-20 16:07:12 来源:亿速云 阅读:93 作者:柒染 栏目:大数据

Spring MVC Controller单例陷阱是什么,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

Spring MVC Controller默认是单例的

以下是测试步骤,代码与结果.

1. 如果是单例类型类的,那么在Controller类中的类变量应该是共享的,如果不共享,就说明Controller类不是单例。以下是测试代码:

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

@Controller

public class ExampleAction {

    private int singletonInt=1;

     @RequestMapping(value = "/test")

     @ResponseBody

     public String singleton(HttpServletRequest request,

             HttpServletResponse response) throws Exception {

         String data=request.getParameter("data");

         if(data!=null&&data.length()>0){

             try{

              int paramInt= Integer.parseInt(data);

             singletonInt = singletonInt + paramInt;

             }

             catch(Exception ex){

                 singletonInt+=10;

             }

         }else{

             singletonInt+=1000;

         }

         return String.valueOf(singletonInt);

    }

}

分别三次请求: http://localhost:8080/example/test.do?data=15

得到的返回结果如下。

第一次: singletonInt=15

第二次: singletonInt=30

第三次: singletonInt=45

从以上结果可以得知,singletonInt的状态是共享的,因此Controller是单例的。

单例的原因有二:

1、为了性能。

2、不需要多例。

1、这个不用废话了,单例不用每次都new,当然快了。

2、不需要实例会让很多人迷惑,因为spring mvc官方也没明确说不可以多例。

  我这里说不需要的原因是看开发者怎么用了,如果你给controller中定义很多的属性,那么单例肯定会出现竞争访问了。

  因此,只要controller中不定义属性,那么单例完全是安全的。下面给个例子说明下:

package com.lavasoft.demo.web.controller.lsh.ch6;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * Created by Administrator on 14-4-9.
 *
 * @author leizhimin 14-4-9 上午10:55
 */
@Controller
@RequestMapping("/demo/lsh/ch6")
@Scope("prototype")
public class MultViewController {
    private static int st = 0;      //静态的
    private int index = 0;          //非静态
    @RequestMapping("/show")
    public String toShow(ModelMap model) {
        User user = new User();
        user.setUserName("testuname");
        user.setAge("23");
        model.put("user", user);
        return "/lsh/ch6/show";
    }
    @RequestMapping("/test")
    public String test() {
        System.out.println(st++ + " | " + index++);
        return "/lsh/ch6/test";
    }
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI