Spring控制器是否是线程安全的

Edg*_*ase 11 java spring

我遇到了这个控制器示例,我想知道它是否是线程安全的?我特别想知道gson实例变量.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class TestController {

    private final Gson gson = new Gson();

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public void test(HttpServletResponse res, HttpServletRequest req) throws IOException {
        HashMap<String, String> hm = new HashMap();
        res.getWriter().print(gson.toJson(results));
        res.getWriter().close();
    }
}
Run Code Online (Sandbox Code Playgroud)

dig*_*oel 12

为了回答标题"弹簧控制器线程安全"中的问题,Spring控制器是单例,因此它们应该以线程安全的方式实现,但是由您来确保您的实现实际上是线程安全的.

在您发布的代码中,您应该没问题,因为正如其他人指出的那样,GSON是线程安全的.