Currently we have an application who use spring who support mysql. Some people prefer to use Oracle. So i search a way with spring to have an abstract factory with a factory for every database and each one have a dao. How to put the glue between all this component? How the component know the datasource who need to be used? Is there some good pratice with spring to do this?
Asked
Active
Viewed 377 times
0
-
Grabbing a connection from either pool/factory depending a condition? If so make it clearer in your question – ssedano Jun 23 '12 at 11:18
1 Answers
3
Not clear what exactly is your problem, but Spring profiles are answer to all of them. First you need to define two DataSource
s for each supported database:
<bean id="oracleDataSource" class="..." profile="oracle">
<!-- -->
</bean>
<bean id="mysqlDataSource" class="..." profile="mysql">
<!-- -->
</bean>
Note the profile
attribute. Actually you will probably get away with simply parametrizing one data source yo use different JDBC URL and driver, but doesn't matter.
Now you define two versions of each DAO: one for Oracle and one for MySQL:
interface MonkeyDao {
//...
}
@Repository
@Profile("oracle")
class OracleMonkeyDao implements MonkeyDao {
//...
}
@Repository
@Profile("mysql")
class MySqlMonkeyDao implements MonkeyDao {
//...
}
As you can see you have two beans defined implementing the same interface. If you do it without profiles and then autowire them:
@Resource
private MonkeyDao monkeyDao;
Spring startup will fail due to unresolved dependency. But if you enable one of the profiles (either mysql
or oracle
) Spring will only instantiate and create bean for matching profile.

Tomasz Nurkiewicz
- 334,321
- 69
- 703
- 674
-
ok and we enable profile via application-context.propertie and i should put something like: spring.profiles.active=mysql seem interesting any other suggestion? – robert trudel Jun 23 '12 at 11:19
-
@roberttrudel: you mean other approaches? Check out [my answer with `include`](http://stackoverflow.com/a/9951115/605744) – Tomasz Nurkiewicz Jun 23 '12 at 11:55