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.
Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext ). Scopes a single bean definition to a single object instance per Spring IoC container.
You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.
The default scope is singleton.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With