问题
Consider the following classes' structure:
BaseDAO
with methods to crest PreparedStatement and get connection from poolAccountDAO extends BaseDAO
to work withAccount
table via JDBC. This class is singletonAccountService
witch calls methods of AccountDAO like this:AccountDAO.getInstance().login(name, password).
AccountDAO
is a Spring bean with @Transactional
annotations to methods that insert some data.
Is this OK? I think singleton DAO classes can cause performance problems. May be it is better to use some spring injections into service layer classes? (I'm new to Spring, so any advice will be appriciated)
回答1:
The recommended approach in the Spring documentation is to write your DAOs as normal classes and use the singleton scope. This will work fine if your DAOs maintain no state.
http://static.springsource.org/spring/docs/2.0.x/reference/beans.html#beans-factory-scopes-prototype
section 3.4.2.
If you are using Spring, you shouldn't need to deal with prepared statements and whatnot, unless you are doing something wonky. Look at JdbcTemplate or HibnerateTemplate. Yes, you should wire Spring to inject your DAOs into your services or wherever you need to use them.
回答2:
I am not too familiar with Spring but in general you don't want the connections to your data sources to be accessed from multiple threads. It is probably O.K. if you configure it so that the DAO objects are pseudo-singletons within a thread context but are not shared across threads. Most IoC containers will allow you to do this through configuration.
Of course, this brings other considerations about data consistency into play and you have to manage those carefully. Generally the ORM part will help you with that though.
来源:https://stackoverflow.com/questions/3937548/is-it-ok-to-have-singleton-dao-objects