6
votes

I have seen it written at many places that DAO and Service classes of a spring application should be singleton scoped.
In my application I have the following service class

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDAO customerDAO;

    .......
    parameterised methods only....
}  

and a DAO class

@Repository
public class CustomerDAOImpl implements CustomerDAO {

@Autowired
private SessionFactory sessionFactory;

...............
parameterised methods only....
}  

Since I haven't defined any scope, the default scope is singleton.So both the CustomerService and CustomerDAO will be instantiated only once per the container.Also the DAO class will be autowired to the Service class only once at the beginning.Since it is going to be a heavy request web application, that means (OR does that mean ?) hundreds of threads are going to use the same instances of both the classes.

Then how thread safety is guaranteed in this case ?
And what about the scope of hibernate sessionfactory bean defined in the xml ?

I am very much confused about the bean scopes and thread safety in a spring mvc application. Springsource documentation doesn't clearly explain these for a web application.

Could anyone please explain me the best practises of using bean scopes(for DAO, Service, Controller and other beans) for a heavy request web application ?
Any link which explains these woulb be grateful for me.

Thanks for your suggestions in advance.

1

1 Answers

5
votes

As long as your service and DAO singletons do not hold state (don't hold instance variables - other beans excepted - manipulated inside methods), there is no problem regarding thread safety.

Regarding session factory, the default hibernate session scope in spring web-app is based on the "one hibernate session per request" pattern, which means that you will have one session for each http request (thread) and so no reason to worry about concurrency neither.