java 实现aop需要spring相关依赖。
本文基于注解实现aop。
一、定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface AopLog {
/**
* 根据需要自定
* @return string
*/
String value() default "";
}
二、业务方法demo
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* TODO
*
* @author cherrytang
* @version 1.0
* @date 2018/5/29
*/
@Component("aopTest")
@Slf4j
public class AopService {
@AopLog("注解值")
public void doService(int id,String name){
log.info("调用方法,处理具体业务");
}
}
三、实现aop类
import lombok.extern.slf4j.Slf4j;
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.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.stream.Collectors;
@Aspect
@Component
@Slf4j
public class AspectAop {
/**
* 切入点方法一:注解:会对加了指定注解的方法 进行aop操作。比较灵活,注解可以携带信息,但不适用于方法太多的情况
*/
@Pointcut("@annotation(com.aop.AopLog)")
public void aopMethod1(){}
/**
* 切入点方法二: 切入点表达式
*/
@Pointcut("execution(* com.aop.AopService.*(..))")
public void aopMethod2(){}
@Around("aopMethod1()")
public Object handl(ProceedingJoinPoint pjo ) throws Throwable {
MethodSignature methodSignature = (MethodSignature) pjo.getSignature();
// 获取方法参数列表
String[] parameterNames = methodSignature.getParameterNames();
//获取注解
AopLog aopLog = methodSignature.getMethod().getAnnotation(AopLog.class);
//获取传入的参数
Object[] args = pjo.getArgs();
log.info("注解值="+ (aopLog != null ? aopLog.value() : ""));
log.info("方法名="+methodSignature.getMethod());
log.info("参数名称="+Arrays.stream(parameterNames).collect(Collectors.joining(",")));
log.info("参数值="+Arrays.stream(args).map(String::valueOf).collect(Collectors.joining(",")));
//调用方法
Object obj = pjo.proceed();
log.info("运行结果:"+obj);
return obj;
}
}
四、编写测试类,检查结果。
import com.AopDemoApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* TODO
*
* @author cherrytang
* @version 1.0
* @date 2018/5/29
*/
@SpringBootTest(classes = AopDemoApplication.class)
@RunWith(SpringRunner.class)
public class AopTest {
@Autowired
AopService aopService;
@Test
public void aopServiceTest(){
aopService.doService(1,"develon");
}
}
运行结果: