this is annotations Code:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface PreVisit {
String value();
}
this use in the Controller @PreVisit("@pv.hasAccess('xxxxxx')")
@PreVisit("@pv.hasAccess('xxxxxx')")
@RequestMapping(value = "getUser")
public User getUser(Integer userId) {...some code...}
this is pv.hasAccess('xxxxxx') code:
@Service("pv")
public class PageVisit{
public boolean hasAccess(String par){
//return false or true;
}
}
My question:
In Aspect, how do you get methods in annotation parameters and get the result of execution
this is Aspect file code:
@Aspect
@Component
public class PreVisitAspect {
@Around("@annotation(PreVisit)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
//How do I get the result of the method execution in the annotation parameter here
//boolean pvResult=@pv.hasAccess('xxxxxx'); pvResult=false or true
//Do something use the pvResult
}
}
I'm the questioner
I have solved this using Java reflection,as follows:
@Aspect
@Component
public class PreVisitAspect {
@Autowired
private PageVisit pv;
@Around("@annotation(preVisit)")
public Object around(ProceedingJoinPoint joinPoint, PreVisit preVisit) throws Throwable {
String value = preVisit.value();
//String value="@pas.hasAccess('xxxxxx')";
if(value.startsWith("@")){
String beanName=value.substring(value.indexOf("@")+1,value.indexOf("."));
String methodName=value.substring(value.indexOf(".")+1,value.indexOf("("));
String paramsStr=value.substring(value.indexOf("(")+2,value.lastIndexOf(")")-1);
Object[] paramsArr=paramsStr.split("','");
logger.info("beanName:"+beanName);
logger.info("methodName:"+methodName);
logger.info("paramsStr:"+paramsStr);
ServletContext servletContext = request.getSession().getServletContext();
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
Method method = ReflectionUtils.findMethod(appContext.getBean(beanName).getClass(), methodName,new Class[]{String.class} );
Boolean result = (Boolean)ReflectionUtils.invokeMethod(method, appContext.getBean(beanName),paramsArr);
logger.info(result.toString());
}
.....other Code.....
}
}
tks @Karthikeyan Vaithilingam