lundi 30 mars 2015

Java - How to combine @InitBinder(for Validation) and @Aspect(Logging) annotations and use it in Spring Controller?

Currently we are migrating a Struts 1.1 project into Spring 4.x.


We have successfully converted Action class to Controller and formbean to Model and even we are able to convert struts validation to Spring validation.


But we are facing an issue when we try to add AOP for all the controllers. The purpose is to add a log for measuring the time taken for all the controller methods.


below is code snippet,



@Component
@Controller
public class LoginController {

@Autowired
private LoginValidator loginValidator;

@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(loginValidator);
}

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String loginUser(@Valid @ModelAttribute Login form, BindingResult bindingResult) {
System.out.println("Entering loginController.loginUser method");
}
}


We are using the below point-cut to apply aop,



import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class Logging {

@Pointcut("execution(* com.controller.*.*(..))")
public void businessLogicMethods() {}

@Around("businessLogicMethods()")
public Object logAround(ProceedingJoinPoint jp) {

System.out.println("around() is running!");
System.out.println(jp.getSignature().getName());
System.out.println(jp.getArgs());
Object obj = null;
try {
obj = jp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("******");
return obj;
}
}


Either Validation or AOP is working at a time. If AOP is not applied then Validation fired. If aop is applied only AOP is fired.


Can anyone help this?


Thanks...


Aucun commentaire:

Enregistrer un commentaire