Spring自动装配和线程安全性

8

我是Spring的新手,最近创建了一个测试RESTful web服务应用程序。我正在遵循Spring的@Autowiring方式来注入bean。以下是我的代码和一个问题:

@Service
public class HelloWorld {       

    @Autowired
    private HelloWorldDaoImpl helloWorldDao;

    public void serviceRequest() {
        helloWorldDao.testDbConnection();
    }

}

@RestController
public class HelloWorldController {

    @Autowired
    private HelloWorld helloWorld;

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String test() {
        helloWorld.serviceRequest();
        return "Success";
    }
}

现在我的问题是,当我有两个请求同时到达,并且它们都共享同一个Service类变量“helloWorld”时,我们如何确保返回给请求1的值不会传递给请求2,反之亦然?
使用@Autowired时,Spring是否自动处理此类多线程问题?
2个回答

8

Spring本身并不会照顾您应用程序的线程安全,尤其是因为这发生在完全不同的层上。自动装配(和Spring代理)与此无关,它只是将依赖组件组装成一个工作整体的机制。

您提供的示例也不是非常具有代表性,因为您展示的两个bean实际上是不可变的。没有共享状态可以由并发请求重复使用。为了说明Spring实际上并不关心您的线程安全性,您可以尝试以下代码:

@Service
public class FooService {       
    // note: foo is a shared instance variable
    private int foo;

    public int getFoo() {
        return foo;
    }

    public void setFoo(int foo) {
        this.foo = foo;
    }
}

@RestController
public class FooController {

    @Autowired
    private FooService fooService;

    @RequestMapping(value = "/test")
    public String test() {
        int randomNumber = makeSomeRandomNumber();
        fooService.setFoo(randomNumber);
        int retrievedNumber = fooService.getFoo();
        if (randomNumber != retrievedNumber) {
            return "Error! Foo that was retrieved was not the same as the one that was set";
        }

        return "OK";
    }
}

如果你对这个端点进行压力测试,你肯定迟早会得到错误消息——Spring 不会采取任何措施来防止你自己给自己惹麻烦。


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接