One solution that you can use to solve problems related to your business rules is using Spring AOP. What you can do is define an annotation (e.g. @X) and place that annotation on top of your POST request.
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface X{}
Next, you need to do, create an aspect and run your validation logic in this aspect as follows:
@Aspect @Component public class CustomAspect { //You can autowire beans here @Around("@annotation(qualified name of X)") public Object customMethod(ProceedingJoinPoint joinPoint) throws Throwable { flag = customLogic(); if (flag){ return joinPoint.proceed(); //return if logic passes, otherwise }else{ throw new BusinessRuleException("Business rule violated"); } } private boolean customLogic(){ //your custom logic goes here } }
And finally, apply this annotation on top of any method in the controller layer, for example:
@X @RequestMapping(method = RequestMethod.POST, value = "do-something") public void callSomething(HttpServletRequest request) throws Exception {
The only thing to note above is that you must explicitly pass the HttpServletRequest request to your controller method so that the AOP aspect gets the same context for manipulating attributes associated with the user's session, such as session_id, etc.
The above solution will help you add business rules on top of your business logic and will help you with all kinds of preliminary checks that you want to create in your web application. This is a pretty handy Spring AOP application. Stretch out in case of any
source share