千家信息网

Spring MVC Controller单例陷阱是什么

发表于:2025-02-04 作者:千家信息网编辑
千家信息网最后更新 2025年02月04日,Spring MVC Controller单例陷阱是什么,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。Spring MV
千家信息网最后更新 2025年02月04日Spring MVC Controller单例陷阱是什么

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";    }}

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

0