I got a problem when implement DDD with Spring. This problem is “Is Domain Object need to declare to Spring bean?”.
What do you think this problem?
In past, I’m thought that Domain Object is not absolutely declared Spring Bean.
But I’m confused that implement it example for DDD with Spring.
Because Domain Object had Data and Behavior(Business Logic), it is need to directly dependencies with other layer class(specific Repository or Infrastructure layer).
class Board {
private BoardRepository repository;
public void insert() {
repository.insert(this);
}
...
}
Once I progress toward declaration to Bean.
This is point of problem. If we use ORM as Hibernate, Domain Object take the responsibility of Entity and Spring’s Bean at a time.
@Entity
@SequenceGenerator(name = "BoardId_Seq", sequenceName = "BoardId_Seq")
class Board {
...
}
Because creation of Domain Object is executed to inner ORM, need to additional code for DI.
For example,
class BoardServiceFacade ...{
...
public Long insertBoard(Board board) {
Board boardBean = domainFactory.newBoard(board);
boardBean.insert();
return boardBean.getId();
}
}
class DomainFactory ...{
public Board newBoard(Board board) {
Board boardBean = newInitializedBoard(board);
return boardBean;
}
}
Work flow is next for persist to Board instance :
1. insertBoard method called with Board instance that is got Client(layer).
2. domainFactory.newBoard() called with Board instance
3. create new Spring’s Bean instance(this bean has prototype bean scope) with initialized(resolved?) dependencies.
4. domain object’s value is copied to created Spring’s Bean from got instance from Client.
finally, Board instance that Spring’s Bean do persist method(insert()).
Opps. very complexity..
This complexity is caused by declared to Spring’s Bean for Domain Object.
If Domain Object is not declared Spring’s Bean, it’s code is not necessity!
I found very elegance solution in this article.
@Configuarble is introduced Spring 2.0. This annotation is possibe to injection of dependenies only add it by container.
@Configurable
...
class Board {
private BoardRepository repository;
public void insert() {
repository.insert(this);
}
...
}
very nice and very convenience.
reference article : Spring framework and DDD(Domain-Driven Design) – for korean.