java之CGLIB动态代理
© 版权声明:本文为博主原创文章,转载请注明出处
CGLIB动态代理:
CGLIB动态代理就是对指定的类生成一个子类,覆盖其中所有的方法并环绕增强
优势:
- 1. 业务类只需要关注业务逻辑本身,保证了业务类的重用性
- 2. 只需一个动态代理类就可以代理很多类,大大减少了代理类的规模,便于维护
- 3. 接口变了,动态代理类也不需要任何改动
- 4. 可以代理没有实现任何一个接口的类
劣势:
- 1. 不可以对final修饰的类或方法进行代理
实例:
1.项目结构
2.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.proxy</groupId> <artifactId>DynamicProxy-CGlib</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- Junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- CGLIB --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.2.5</version> </dependency> </dependencies> </project>
3.Hello.java
package org.proxy.DynamicProxy_CGlib; public class Hello { public void say(String name) { System.out.println("Hello!" + name); } }
4.CGLibProxy.java
package org.proxy.DynamicProxy_CGlib; import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class CGLibProxy implements MethodInterceptor { private static CGLibProxy instance = new CGLibProxy(); private CGLibProxy() { } public static CGLibProxy getInstance() { return instance; } @SuppressWarnings("unchecked") public <T> T getProxy(Class<T> cls) { return (T) Enhancer.create(cls, this); } public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { before(); Object result = proxy.invokeSuper(obj, args); after(); return result; } private void before() { System.out.println("Before"); } private void after() { System.out.println("After"); } }
5.TestCGLibDynamicProxy.java
package org.proxy.test; import org.junit.Test; import org.proxy.DynamicProxy_CGlib.CGLibProxy; import org.proxy.DynamicProxy_CGlib.Hello; public class TestCGLibDynamicProxy { @Test public void testHello() { Hello helloProxy = CGLibProxy.getInstance().getProxy(Hello.class); helloProxy.say("Jack"); } }
6.效果预览
参考:《架构探险-从零开始写Java Web框架》(黄勇著)
© 版权声明:本文为博主原创文章,转载请注明出处