Biography: Swing unruly, love life. Java Cultivator (wechat official ID: Java Cultivator), welcome to follow. Access to 2000G of detailed information on the 2020 interview questions

Let’s verify this simply:

package com.riemann.springbootdemo.controller; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * @author riemann * @date 2019/07/29 22:56 */ @Controller public class ScopeTestController { private int num = 0; @RequestMapping("/testScope") public void testScope() { System.out.println(++num); } @RequestMapping("/testScope2") public void testScope2() { System.out.println(++num); }}Copy the code

We first go to http://localhost:8080/testScope, the answer is 1; Then we visit http://localhost:8080/testScope2 again, the answer is 2.

Get different values, which is thread unsafe.

@Scope(“prototype”)

package com.riemann.springbootdemo.controller; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * @author riemann * @date 2019/07/29 22:56 */@Controller@Scope("prototype") public class ScopeTestController { private int num = 0; @RequestMapping("/testScope") public void testScope() { System.out.println(++num); } @RequestMapping("/testScope2") public void testScope2() { System.out.println(++num); }}Copy the code

We are still first visit http://localhost:8080/testScope, the answer is 1; Then we could visit http://localhost:8080/testScope2, the answer is 1.

I believe you can easily find:

Singletons are unsafe and lead to repeated use of attributes.

The solution

  • Do not define member variables in controller.

  • In case you have to define a non-static member variable, use the @scope (” prototype “) annotation to set it to multi-example mode.

  • Use the ThreadLocal variable in the Controller

added

Spring Bean scopes have the following five:

Singleton: When Spring creates the applicationContext container, spring wants to initialize all instances of that scope. Lazy init is used to avoid preprocessing.

Prototype: Every time you get the bean from getBean, a new instance will be created and spring will no longer manage it.

(The following is for web projects only)

Request: a new instance is created every time a request is made. This is different from prototype.

Session: indicates each session.

Global Session: A global Web domain, similar to the Application in servlets.

The answer:

Controllers are singletons by default; do not use non-static member variables, otherwise data logic will be messed up. Singletons are not thread-safe because of them.