I\'m trying to use something similar to org.springframework.cache.annotation.Cacheable
:
Custom annotation:
@Target(ElementType.METHOD)
Adding another simpler way of doing it using Spring Expression. Refer below:
Your Annotation:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckEntity {
String message() default "Check entity msg";
String keyPath() default "";
}
Your Service:
@Service
@Transactional
public class EntityServiceImpl implements EntityService {
@CheckEntity(keyPath = "[0]")
public Entity getEntity(Long id) {
return new Entity(id);
}
@CheckEntity(keyPath = "[1].otherId")
public Entity methodWithMoreThanOneArguments(String message, CustomClassForExample object) {
return new Entity(object.otherId);
}
}
class CustomClassForExample {
Long otherId;
}
Your Aspect:
@Component
@Aspect
public class CheckEntityAspect {
@Before("execution(* *.*(..)) && @annotation(checkEntity)")
public void checkEntity(JoinPoint joinPoint, CheckEntitty checkEntity) {
Object[] args = joinPoint.getArgs();
ExpressionParser elParser = new SpelExpressionParser();
Expression expression = elParser.parseExpression(checkEntity.keyPath());
Long id = (Long) expression.getValue(args);
// Do whatever you want to do with this id
// This works for both the service methods provided above and can be re-used for any number of similar methods
}
}
PS: I am adding this solution because I feel this is a simpler/clearner approach as compared to other answers and this might be helpful for someone.