java - Spring Controller 是线程安全的吗

标签 java spring

我遇到了这个 Controller 示例,想知道它是否是线程安全的?我特别想知道 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();
    }
}

最佳答案

要回答标题“Spring Controller 是否线程安全”中的问题,Spring Controller 是单例的,因此它们应该以线程安全的方式实现,但您需要确保您的实现实际上是线程安全的。

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

关于java - Spring Controller 是线程安全的吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14145761/

相关文章:

java - Android Actionbar 具有后退导航和下拉列表

java - ECDSA算法教程来签署一个字符串

java - Spring Boot或者Tomcat缓存静态资源,每次刷新都得重新构建

java - 使用Apache POI在Excel中使用千位分隔符格式化数字

java - 我正在使用 xml 配置使用 angularjs 实现 spring security,但出现与 CSRF token 相关的错误

java - Spring - 使用 hibernate 和 spring security 扩展类

java - PropertyPlaceholderConfigurer 用于查找数据库值并使用属性文件作为后备

java - 使用 IAM 凭证通过 JDBC 从 Spring 连接到 AWS Aurora 是否合适?

Spring mvc 应用程序在 tomcat 中不能作为 war 运行,但在 IDE 中运行良好

java - Mockito 中泛型方法的 ArgumentCaptor