经常有人问我spring的aop讲一下好不,aop到底是啥,好难理解哦,aop的概念很多,但光听概念往往不太明白,aop的实现有很多,今天我介绍下用jdk中的Proxy如何实现aop机制
1. ITestService.java
package com.joey.aop.service;
public interface ITestService {
/**
* 定义一个doSomething方法
*
* @param str 输入字符串
* @return String 返回"return " + str
*/
public String doSomething(String str);
}
package com.joey.aop.service.impl;
import com.joey.aop.service.ITestService;
public class TestService implements ITestService {
@Override
public String doSomething(String str) {
// 执行dosomething 输出 do something 字符串
System.out.println("do someting");
return "return " + str;
}
}
3. AopHandler.java
package com.joey.aop.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class AopHandler implements InvocationHandler {
private Object service;
public AopHandler(Object service) {
this.service = service;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 前置处理
System.out.println("before something");
// 执行方法
Object result = method.invoke(service, args);
// 后置处理
System.out.println("after something");
// 返回数据
return result;
}
}
4. Main.java
package com.joey.aop.main;
import com.joey.aop.proxy.AopHandler;
import com.joey.aop.service.ITestService;
import com.joey.aop.service.impl.TestService;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
// 实例化对象
ITestService testService = new TestService();
// 生成代理对象
Object proxy = Proxy.newProxyInstance(Main.class.getClassLoader(), new Class[]{ITestService.class}, new AopHandler(testService));
if (proxy instanceof ITestService) {
ITestService proxyService = (ITestService) proxy;
// 执行代理对象的doSomething方法
System.out.println(proxyService.doSomething("joey"));
}
}
}
5. 输出结果
before something
do someting
after something
return joey
发现doSomething方法前置输出了before something, 后置输出了after something, 实现aop机制成功
