6

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);
    }
}
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311

1 Answers1

14

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.

Joeri Hendrickx
  • 16,947
  • 4
  • 41
  • 53
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • thanks (again), to make them pure stateless, I could use method local instances of dao etc, but this would therefore be much slower and resource heavy as a new object would be created for each request/thread, and thus ill advised as I know they will not change ? – NimChimpsky Jun 25 '12 at 13:13
  • @NimChimpsky: there is no point in using local variables in this case (and how would you obtain them from the context)? – Tomasz Nurkiewicz Jun 25 '12 at 13:23
  • I mistakingly thought they were would get injected at runtime but you can't annotate within methods. – NimChimpsky Jun 25 '12 at 13:29
  • Does that mean that in designing a controller that is used to handle a form submission, you should be worried about Controller and the Service that is injected using Autowired annotation? – Daniel Newtown Sep 16 '15 at 01:37