首先创建注解:用来标记方法是否需要判断执行
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface JudgeMethod{
String daoName() default "ipDao";
}
在需要判断的是否执行的方法上面加上注解
@JudgeMethod
public String execute(){
// 发送信息
return sendMsg();
}
利用spring的aop功能实现判断是否执行发送信息方法
@Aspect
@component
public class JudgeMethodAspect implements ApplicationContextAware{
private ApplicationContext applicationContext;
@Autowired
private IpJudgeService ipJudgeService ;
@Override
public setApplicationContext(ApplicationContext applicationContext ){
this.applicationContext = applicationContext;
}
@Pointcut("@annotation(com.wei.annotation.JudgeMethod)")
public void judgeMethodPointCut(){
}
@Around("judgeMethodPointCut()")
public void around(ProceedingJoinPoint pjp) throws Throwable{
try{
String methodName = pjp.getSignature().getName();
Class<?> targetClass = pjp.getTarget().getClass();
Class[] parameterTypes =
((MethodSignature)pjp.getsignature()).getParameterTypes();
Method methodClass = targetClass.getMethod(methodName,parameterTypes):
JudgeMethod judgeMethod =
(JudgeMethod)methodClass.getAnnotation(JudgeMethod.class);
String ipDaoName = judgeMethod.daoName();
IpDao ipDao = this.ApplicationContext.getBean(ipDaoName,IpDao.class);
if(ipJudgeService.JudgeIsExecute(ipDao)){
pjp.proceed();
}else{
System.out.printlp("不匹配不执行该方法:" + methodName):
}
}catch(Exception e){
System.err.printlp(e):
throw e;
}
}
}
利用spring的aop功能实现打印和修改参数,使用表达式带入注解方法
@Aspect
@component
public class JudgeMethodAspect implements ApplicationContextAware{
private ApplicationContext applicationContext;
@Autowired
private IpJudgeService ipJudgeService ;
@Override
public setApplicationContext(ApplicationContext applicationContext ){
this.applicationContext = applicationContext;
}
@Pointcut("@annotation(com.wei.annotation.JudgeMethod)")
public void judgeMethodPointCut(){
}
@Around("judgeMethodPointCut() && @Annotation(judgeMethod)")
public void around(ProceedingJoinPoint pjp,JudgeMethod judgeMethod) throws Throwable{
String servicaIp;
try{
String ipDaoName = judgeMethod.daoName();
IpDao ipDao = this.ApplicationContext.getBean(ipDaoName,IpDao.class);
if(ipJudgeService.JudgeIsExecute(ipDao)){
Object[] params = pjp.getArgs();
for(int i=0;i<params.length;i++){
System.out.printlp("参数:" + params[i]):
}
pjp.proceed(params);
}else{
System.out.printlp("不匹配不执行该方法:" + methodName):
}
}catch(Exception e){
System.err.printlp(e):
throw e;
}
}
}