使用Spring MVC在服务层验证

时间:2014-09-03 03:33:23

标签: java spring-mvc backend service-layer

我想知道如何执行干净的代码来组织我的服务层验证。

所以,我有这项服务:

public interface PersonService {

        public Person getPerson(int idperson);   
        public List   getPeopleWithFather( int idFather); 
}

对于服务层的验证,我使用Spring AOP(Aspectj),因此要验证第一种方法:

 public Person getPerson(int idperson){
     return personRepository.getPerson(idperson);
 }


@AfterReturning( 
            pointcut="execution(* business.PersonService.getPerson(..))",
            returning = "result")
    public void afterRunning(JoinPoint joinPoint, Object result){
        Person person = (Person) result;       
        if(person == null){
            throw new PersonNotFound();
        }
    }

所以在我的服务中,我不需要编写try / catch或者验证条件。但是,我不知道如何为第二种方法组织我的代码,因为:

  1. 首先,我需要验证父亲是否存在他的身份。
  2. 获取孩子名单。
  3. 一种方法是这样做:

    public List   getPeopleWithFather( int idFather){
        Person father = getPerson(idFather);
        if(father != null){ return personRepository.getPeopleWithFather(father);  }
        return null;
    }
    

    其他方式是:

        public List   getPeopleWithFather( int idFather){
            Person father = ((PersonService) AopContext.currentProxy() ).getPerson(idFather);
            return personRepository.getPeopleWithFather(father);
        }
    
    @AfterThrowing(pointcut="execution(* business.PersonService.getPeopleWithFather(..))",
                throwing = "throwable")
        public void afterThrowing(JoinPoint joinPoint, Exception throwable){
            if( throwable instanceof PersonNotFound){
               throw  new PersonNotFound("whatever");
            }
        }
    

    有一种更优雅的方式来执行这些验证吗?提前谢谢。

0 个答案:

没有答案
相关问题