在完全投入领域事件之前,我们先完善Management领域限界上下文:
package com.lugew.domaindrivendesignwithspringboot.management;import com.lugew.domaindrivendesignwithspringboot.sharedkernel.Money;import lombok.Getter;import lombok.Setter;import javax.persistence.*;@Entity@Getter@Setterpublic class HeadOfficeDto {@Id@GeneratedValueprivate long id;private float balance;private int oneCentCount;private int tenCentCount;private int quarterCount;private int oneDollarCount;private int fiveDollarCount;private int twentyDollarCount;@Transientprivate float amount;@PostLoadpublic void setAmount() {amount = oneCentCount * 0.01f + tenCentCount * 0.10f + quarterCount * 0.25f+ oneDollarCount * 1f+ fiveDollarCount * 5f + twentyDollarCount * 20f;}public HeadOffice convertToHeadOffice() {HeadOffice headOffice = new HeadOffice();headOffice.setId(id);headOffice.setBalance(balance);headOffice.setCash(new Money(oneCentCount, tenCentCount, quarterCount,oneDollarCount, fiveDollarCount, twentyDollarCount));return headOffice;}}
重启应用,在浏览器查看http://localhost:23333/h2-console:
接下来为HeadOffice添加变更手续费方法:
package com.lugew.domaindrivendesignwithspringboot.management;import com.lugew.domaindrivendesignwithspringboot.common.AggregateRoot;import com.lugew.domaindrivendesignwithspringboot.sharedkernel.Money;import lombok.Getter;import lombok.Setter;import static com.lugew.domaindrivendesignwithspringboot.sharedkernel.Money.None;@Getter@Setterpublic class HeadOffice extends AggregateRoot {private float balance;private Money cash = None;public void changeBalance(float delta) {balance += delta;}public HeadOfficeDto convertToHeadOfficeDto() {HeadOfficeDto headOfficeDto = new HeadOfficeDto();headOfficeDto.setId(id);headOfficeDto.setBalance(balance);headOfficeDto.setOneCentCount(cash.getOneCentCount());headOfficeDto.setTenCentCount(cash.getTenCentCount());headOfficeDto.setQuarterCount(cash.getQuarterCount());headOfficeDto.setOneDollarCount(cash.getOneDollarCount());headOfficeDto.setFiveDollarCount(cash.getFiveDollarCount());headOfficeDto.setTwentyDollarCount(cash.getTwentyDollarCount());return headOfficeDto;}}
再添加资源库:
package com.lugew.domaindrivendesignwithspringboot.management;import org.springframework.data.repository.CrudRepository;public interface HeadOfficeRepository extends CrudRepository<HeadOfficeDto, Long> {}
最后根据需求创建一个HeadOffice,我们直接提供获取实体的单例:
package com.lugew.domaindrivendesignwithspringboot.management;import lombok.RequiredArgsConstructor;import org.springframework.stereotype.Component;@Component@RequiredArgsConstructorpublic class HeadOfficeInstance {private final HeadOfficeRepository headOfficeRepository;private static final long HeadOfficeId = 1;private HeadOfficeDto headOfficeDto;public HeadOfficeDto getInstance() {return headOfficeRepository.findById(HeadOfficeId).orElse(null);}}
还有一个问题,这个类属于洋葱架构的哪个位置?它看起来和资源库相似,所以属于资源库相同的层级,此层中的类是不能被内层应用的,只能被相同或上层引用。这个类有别与资源库,因为它维持了一个实例对象,所以不能由资源库来行使。
准备工作已完成,我们将ATM和HeadOffice两者联系起来。
