springmvc 是单例还是多例呢

springmvc默认是单例的。

我们可以通过以下代码就能可以验证:

@RestController
@RequestMapping(value = "hello")
public class HelloController {

    private int i = 0;

    @RequestMapping(value = "test1")
    public int testSingle1() {
        ++i;
        return i;
    }

    @RequestMapping(value = "test2")
    public int testSingle2() {
        ++i;
        return i;
    }
}

定义了一个全局变量,这种写法很少见,因为springmvc追求的就是把变量放在形参中,strust2才会这样写吧。既然这样写了,我们就来验证一下是否是单例吧。

依次访问 
http://localhost:8080/hello/test1 结果为:1 
http://localhost:8080/hello/test2 结果为:2 
http://localhost:8080/hello/test1 结果为:3 
可以看出来,没有new 新的对象,所以说是共享一个对象。验证成功。

但是如果我们需要springmvc多例操作时,那也容易,可以修改springmvc的作用域scope

springmvc作用域:

1,single (默认)   

2,prototype 原型模式,每次通过getBean获取该bean就会新产生一个实例,创建后spring将不再对其管理;(完全是为了面试考察,没有实际意义)

实现方式:

使用@Scope("prototype")注解即可将其设置为多例模式

你可能感兴趣的:(springmvc)