作者:偽愛拋棄_514 | 来源:互联网 | 2023-01-14 11:49
看了韩顺平老师的视频后, 忍不住实现简单的AOP功能, 在此再次感谢韩顺平老师, 手动鞠躬!
IService接口
package aop.service;
import java.util.List;
public interface ITestService2 {
void sayBye(List l, int i );
}
Service的实现类(目标对象)
package aop.service.impl;
import java.util.List;
import org.springframework.stereotype.Service;
import aop.service.ITestService2;
@Service
public class TestServiceImpl2 implements ITestService2 {
@Override
public void sayBye(List l,int i ) {
System.out.println("byebyeasdfadf");
}
}
编写通知(自己的通知实现aop的通知(如:前置通知/后置通知))
前置通知:
package aop.advice;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.stereotype.Service;
@Service
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.print(target.getClass().getName() +"."+ method.getName() + "() begin, 入参为:");
for (Object object : args) {
System.out.print(object + " ");
}
}
}
后置通知:
package aop.advice;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.stereotype.Service;
@Service
public class MyAfterReturningAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName() + method.getName() + "() end");
}
}
配置代理对象(ProxyFactoryBean)
以上配置完毕, AOP搞定.
小弟菜鸟, 如有错误, 请不吝指教, 多谢了!