Service - shenliuyang/development GitHub Wiki
这部分练习创建一个Business Facade类,和一个JUnitTest,与我们在Persistence练习中完成的DAO交互。
在这里,我们称它为Manager类,它的主要作用就是在Persistence层和Web层之间作为桥梁,它也用于表现层和数据库层的解耦(例如Swing apps和Web Service中用到的),Managers也应该是你放置任何业务逻辑的地方。
你将要学会两点:
- 如果你仅仅需要基本的CRUD操作,你不需要写Managers;
- 当需要增加自定义的业务逻辑时怎样编写Managers。
在appdot工程中,你并不需要为Manager编写基本的CRUD方法,泛型的基类GenericService帮你实现了这些。
首先,在目录src/java/main/**/service下,创建一个PersonManager接口,定义需要的业务方法。
public interface PersonManager extends GenericService<Person> {
List<Person> getPersonsByFirstName(String firstName);
}
继续我们在Persistence一节中提到的Test-Driven Development(测试驱动开发)思想,我们现在可以创建PersonManagerTest了,放置于src/java/test/**/service/test目录下,在Service层,测试可以使用Mock的思想来实现,Mock将测试目标与外部依赖隔离开,这意味着测试Manager时不需要建立数据库,节省了单元测试运行时间,避免过度测试;并且,在大型项目工程的多人并行开发中,也可以不待Dao写完即完成了Manager的开发。
public class PersonManagerMockTest extends BaseServiceMockTestCase {
private PersonManagerImpl personManager;
@Mock
private PersonDao mockPersonDao;
@Before
public void setUp() {
personManager = new PersonManagerImpl();
personManager.setPersonDao(mockPersonDao);
}
@Test
public void testDeletePerson() {
//正常删除用户.
personManager.remove(-2L);
//删除超级管理用户抛出异常.
try {
personManager.remove(1L);
fail("expected ServicExcepton not be thrown");
} catch (ServiceException e) {
//expected exception
}
}
}
等一下再运行它,因为我们还没有建立PersonManager的实现PersonManagerImpl
这一步是创建PersonManagerImpl类,实现PersonManager中的方法。
在目录src/main/java/**/service/impl下创建PersonManagerImpl.java
package org.appdot.tutorial.service.impl;
import java.util.List;
import org.appdot.tutorial.repository.PersonDao;
import org.appdot.tutorial.entity.Person;
import org.appdot.tutorial.service.PersonManager;
import org.appdot.service.impl.GenericManagerImpl;
import org.springframework.stereotype.Service;
import java.util.List;
//Spring Bean的标识.
@Service("personManager")
public class PersonManagerImpl extends GenericServiceImpl<Person> implements PersonManager {
PersonDao personDao;
/**
* 删除用户,如果尝试删除超级管理员将抛出异常.
*/
@Override
public void remove(Long id) {
if (isSupervisor(id)) {
logger.warn("不能删除超级管理员用户");
throw new ServiceException("不能删除超级管理员用户");
}
super.remove(id);
}
/**
* 判断是否超级管理员.
*/
private boolean isSupervisor(Long id) {
return id == 1;
}
public List<Person> getPersonsByFirstName(String firstName) {
return personDao.findByFirstName(firstName);
}
@Autowired
public void setPersonDao(PersonDao personDao) {
this.repository = personDao;
this.personDao = personDao;
}
}
使用maven命令运行单元测试 “mvn test”