Service Layer inject multiple DAO in practice
Here is a design problem between Dao layer and Service Layer:
In DAO layer, there are DAO Classes called: Dao1, Dao2, Dao3 ...
In Service Layer, there are Service Classes called: Service1, Service2, Service3 ...
Service1 need to inject Dao1, Dao2, Dao3
Service2 need to inject Dao2, Dao3, Dao4
Service3 need to inject Dao3
...
Example for creating a user:
UserService need to inject UserDao to create user, Also UserService need to inject LogDao to record system log information.
It seems there are some repeating work we need to do. Is there any solution in practice? I am using Spring framework. Using @Re开发者_JS百科source annotation to inject these Dao in Service Class.
My solution is: inject all the Dao Class (Dao1, Dao2, Dao3 ...) into DaoCollection Class, then service1, service2, service3... all extends DaoCollection Class. Is it good approach?
Thx
You'd have to define the DAOs that your services use anyway, so you'd have to do that 'repeating' work to some extend.
Depending on the framework you use (if any) that declaration shouldn't be too much overhead (to type).
Example in EJB 3+:
class Service1 {
@EJB private DAO1 dao1;
@EJB private DAO2 dao2;
@EJB private DAO3 dao3;
...
}
I'd say you shouldn't create a common superclass and inject all possible DAOs there. This will most likely make it harder to understand (why are those DAOs there?, are they used?, etc.) and might even have performance issues, depending on the framework in use (you might inject every DAO into each service and thus create a big pool of unused DAO instances).
精彩评论