@EnableAspectJAutoProxy
@Configuration
public class MainConfigAOP {
//业务逻辑类加入到容器中
@Bean
public MathCalculator calculator(){
return new MathCalculator();
}
//切面类加入到容器中
@Bean
public LogAspects logAspects(){
return new LogAspects();
}
}
2.使用@Aspect注解bean 3.配置Advice 4.设置Pointcut
@Aspect
public class LogAspects {
private Class> aClass;
//抽取公共的切入点表达式
//1.本类引用
//2.其他的切面引用
@Pointcut("execution(public int com.xxd.aop.MathCalculator.*(..))")
public void pointCut(){
}
//@Before在目标方法之前切入:切入点表达式(指定在哪个方法切入)
@Before("pointCut()")
public void logStart(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
System.out.println("" + joinPoint.getSignature().getName() + "运行。。。 @Before:参数列表是{" + Arrays.asList(args) + ")");
}
@After("pointCut()")
public void logEnd(JoinPoint joinPoint){
System.out.println("" + joinPoint.getSignature().getName() +"结束。。。 @After");
}
//JointPoint一定要出现在参数表的第一位
@AfterReturning(value = "pointCut()",returning = "result")
public void logReturn(JoinPoint joinPoint,Object result) throws NoSuchFieldException, ClassNotFoundException, IllegalAccessException {
MathCalculator mathCalculator = (MathCalculator)joinPoint.getTarget();
// Class className = joinPoint.getTarget().getClass();
// Class> aClass = Class.forName(className);
// Field field2 = className.getDeclaredField("test");
// field2.setAccessible(true); //暴力反射 获取私有字段必须添加此行
// String test ="";
// MathCalculator mathCalculator = new MathCalculator();
// mathCalculator = (MathCalculator) field2.get(className);
String name = mathCalculator.getName();
System.out.println("获取到了运行中的数据 :" + name +"!!!!");
System.out.println("" + joinPoint.getSignature().getName() + "正常返回。。。 @AfterReturning:运行结果:{" + result +"}");
}
@AfterThrowing(value = "pointCut()",throwing ="exception")
public void logException(JoinPoint joinPoint,Exception exception){
System.out.println("" + joinPoint.getSignature().getName() +"异常。。。 异常信息:{" + exception +"}");
}
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MethodInvocation invocation;
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
Object target = null;
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// The target does not implement the equals(Object) method itself.
return equals(args[0]);
}
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// The target does not implement the hashCode() method itself.
return hashCode();
}
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// There is only getDecoratedClass() declared -> dispatch to proxy config.
return AopProxyUtils.ultimateTargetClass(this.advised);
}
else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
Object retVal;
if (this.advised.exposeProxy) {
// Make invocation available if necessary.
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
// Get as late as possible to minimize the time we "own" the target,
// in case it comes from a pool.
target = targetSource.getTarget();
Class> targetClass = (target != null ? target.getClass() : null);
// Get the interception chain for this method.
//红色的代码是构建代理链,因为一个方法可能有多个切点匹配上,这个时候就需要构建一个链式的执行结构。
List
public List getInterceptorsAndDynamicInterceptionAdvice(
Advised config, Method method, @Nullable Class> targetClass) {
// This is somewhat tricky... We have to process introductions first,
// but we need to preserve order in the ultimate list.
List interceptorList = new ArrayList<>(config.getAdvisors().length);
Class> actualClass = (targetClass != null ? targetClass : method.getDeclaringClass());
boolean hasIntroductions = hasMatchingIntroductions(config, actualClass);
AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
for (Advisor advisor : config.getAdvisors()) {
if (advisor instanceof PointcutAdvisor) {
// Add it conditionally.
PointcutAdvisor pointcutAdvisor = (PointcutAdvisor) advisor;
if (config.isPreFiltered() || pointcutAdvisor.getPointcut().getClassFilter().matches(actualClass)) {
MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
MethodMatcher mm = pointcutAdvisor.getPointcut().getMethodMatcher();
if (MethodMatchers.matches(mm, method, actualClass, hasIntroductions)) {
if (mm.isRuntime()) {
// Creating a new object instance in the getInterceptors() method
// isn't a problem as we normally cache created chains.
for (MethodInterceptor interceptor : interceptors) {
interceptorList.add(new InterceptorAndDynamicMethodMatcher(interceptor, mm));
}
}
else {
interceptorList.addAll(Arrays.asList(interceptors));
}
}
}
}
else if (advisor instanceof IntroductionAdvisor) {
IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
if (config.isPreFiltered() || ia.getClassFilter().matches(actualClass)) {
Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}
else {
Interceptor[] interceptors = registry.getInterceptors(advisor);
interceptorList.addAll(Arrays.asList(interceptors));
}
}
return interceptorList;
}
protected List findCandidateAdvisors() {
// Add all the Spring advisors found according to superclass rules.
List advisors = super.findCandidateAdvisors();
// Build Advisors for all AspectJ aspects in the bean factory.
if (this.aspectJAdvisorsBuilder != null) {
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
}
return advisors;
}