thread safe, stateless design using Spring

对着背影说爱祢 提交于 2019-12-18 11:43:19

问题


I have assumed that if instance variables are managed by spring IOC, and are singletons that the desgin can be called stateless and threadsafe.This type of desgin could consequently be scaled to clustered servers. Am I correct in my assumptions,outlined below ?

@Repository("myDao")
public class MyDao implements Dao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Value("${sqlFoo}")
    private String foo;

    @Override
    public Integer getMyInt(String str) {
      return jdbcTemplate.queryForInt(foo, str);
    }

which is then injected into :

@Service("myService")
public class MyServiceImpl {

    @Resource(name = "myDao")
    Dao dao;

    @Override
    @Transactional(readOnly = true)
    public int getScore(String str) {
      return dao.getMyInt(str);
    }
}

回答1:


Spring beans aren't stateless because they have state (fields). Technically they aren't even immutable because you can change injected fields at any time.

However you can easily make Spring beans immutable by using final fields and constructor injection. Also this kind of state is not problematic from scalability point of view. If your beans contain mutable values that change over time, this is a major issue when clustering. But in Spring services typically contain only dependencies injected at bootstrap time. So they are effectively stateless and immutable.

It doesn't matter on how many servers you run the same Spring application - the beans and dependencies themselves are safe. But if you Spring beans contain counters, caches, mutable maps, etc. - you need to think about them.



来源:https://stackoverflow.com/questions/11189907/thread-safe-stateless-design-using-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!