Guest User

Untitled

a guest
Apr 5th, 2018
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.65 KB | None | 0 0
  1.     //где-то в контроллере
  2.     @AssertEntityExistsById(entityClass = User.class)
  3.     @RequestMapping(value = "/{id}", method = RequestMethod.GET)
  4.     @ResponseBody
  5.     public User getUser(@PathVariable("id") @EntityIdentifier int id) {
  6.         return userService.findUserById(id);
  7.     }
  8.  
  9.     //эдвайс
  10.     @Around("@annotation(assertEntityExistsById) && args(..)")
  11.     public Object assertEntityExists(ProceedingJoinPoint proceedingJoinPoint, AssertEntityExistsById assertEntityExistsById) throws Throwable {
  12.         MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
  13.         Object[] arguments = proceedingJoinPoint.getArgs();
  14.         Object id = null;
  15.  
  16.         List<Parameter> parameters = Arrays.asList(methodSignature.getMethod().getParameters());
  17.  
  18.         for (int index = 0; index < parameters.size(); index++) {
  19.             Parameter parameter = parameters.get(index);
  20.             List<Annotation> parameterAnnotations = Arrays.asList(parameter.getAnnotations());
  21.  
  22.             for (Annotation annotation: parameterAnnotations) {
  23.                 if (annotation instanceof EntityIdentifier) {
  24.                   id = arguments[index];
  25.                 }
  26.             }
  27.         }
  28.  
  29.         Repositories repositories = RepositoriesSingleton.getInstance();
  30.         JpaRepository jpaRepository = (JpaRepository) repositories.getRepositoryFor(assertEntityExistsById.entityClass()).get();
  31.  
  32.         if (!jpaRepository.existsById(id)) {
  33.             throw entityNotFoundExceptionFactory.createForEntityClass(assertEntityExistsById.entityClass());
  34.         }
  35.  
  36.         return proceedingJoinPoint.proceed();
  37.     }
Add Comment
Please, Sign In to add comment