基于接口动态代理的实现
前提:代理类必须实现至少一个接口
- 设置编译环境pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
- 编写接口和实现类
public interface DemoService {
void print();
}
public class DemoServiceImpl implements DemoService {
public void print() {
System.out.println(123);
}
}
- 调用Proxy类中的newProxyInstance方法进行代理实现
public static void main(String[] args) {
// 代理对象
DemoServiceImpl demoService = new DemoServiceImpl();
/**
*
* @参数1 demoService.getClass().getClassLoader()
* 通过代理对象的类加载器,反射获取该类的对象
*
* @参数2 demoService.getClass().getInterfaces()
* 获取该类的实现的所有接口对象
*
* @参数3 new InvocationHandler(){}
* 用于编写增强的代码
*/
// 必须用接口对象进行接收
DemoService service = (DemoService)Proxy.newProxyInstance(demoService.getClass().getClassLoader(),
demoService.getClass().getInterfaces(),
new InvocationHandler() {
/**
*
* @param proxy 代理对象的引用(几乎不用可忽略)
* @param method 执行方法的对象
* @param args 参数对象
* @return
* @throws Throwable
*
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
int j = Integer.parseInt(args[0].toString())*5;
// 执行被代理的方法
System.out.println(method.getName());
method.invoke(demoService,j);
return null;
}
});
service.print(6);
}
基于子类的动态代理
- 设置编译环境pom.xml并导入jar包坐标
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
- 编写Enhancer类中的create方法(后续操作基本和接口代理雷同不再复述)
DemoServiceImpl demoService = new DemoServiceImpl();
Enhancer.create(demoService.getClass(), new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
return null;
}
});
连接点方法 | 指定未被增强的方法 |
切入点方法 | 被增强的方法 |
通知 | 为其它方法进行增强的代码块 |
切面类 | 该类中的方法为其它类作为通知去使用 |
AOP的xml配置
- 导入相应的jar包坐标spring-aspects和 org-aspectj任选其一即可
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!--<dependency>-->
<!--<groupId>org.aspectj</groupId>-->
<!--<artifactId>aspectjweaver</artifactId>-->
<!--<version>1.8.13</version>-->
<!--</dependency>-->
- 导入xml中的头文件注意要下载aop的约束文件
- 编写切面类
- 配置aop,为方法进行加强操作