Consider the following classes' structure:
BaseDAO
with methods to crest PreparedStatement and get connection from poolAccountDAO extends BaseDAO
to work with Account
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)
It is better to create a single instance of your DAO and pass it into the constructor of classes that need it. I tend to avoid singletons whenever I can, because amongst other things, they make your code difficult to test and hide dependencies.
By using singletons in your project, you start to create technical debt. Singletons tend to spread like a virus because it's so easy to access them. It's difficult to keep track of where they're used and getting rid of a singleton can be a refactoring nightmare in large or complex projects.
There are many ways to prevent Singleton pattern from Reflection API, but one of the best solutions is to throw a run-time exception in the constructor if the instance already exists. In this, we can not able to create a second instance.
You cannot destroy an object, only the JVM can do that. Once an object is inaccessible by any live threads, it then becomes eligible for garbage collection. Sounds like something which possibly shouldn't be a Singleton.
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.
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