当前位置:网站首页>Cglib agent - Code enhancement test
Cglib agent - Code enhancement test
2022-07-02 06:22:00 【One eyebrow procedural ape】
Guide pack
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
Write method interceptors
- Method to enhance specific logic
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
import java.util.Arrays;
/** * Customize cglib agent * * @author Ara * @since 2022/6/20 */
public class MyCglibProxyMethodInterceptor<T> implements MethodInterceptor {
/** * Target audience */
private final T target;
/** * Construction method */
public MyCglibProxyMethodInterceptor(T target) {
this.target = target;
}
/** * Get proxy object */
public T getProxyObject(){
Enhancer enhancer = new Enhancer();
// Set parent class because cglib Is to generate a subclass for the specified class to enhance its behavior
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(this);
return (T) enhancer.create();
}
// TODO Perform the enhancement
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println(" Before execution Method parameter : " + Arrays.toString(objects));
Object result = method.invoke(target, objects);
System.out.println(" After execution Return value : " + result);
return result;
}
}
Write the test class to be enhanced
- Enhance target points
/** * article Service * * @author Ara * @since 2022/6/20 */
public class ArticleService {
public String saveArticle(String article) {
System.out.printf(" Save the article [%s]...%n", article);
return article;
}
}
Write tests
- Check whether it can be enhanced
public class MainTest {
public static void main(String[] args) {
ArticleService articleService = new ArticleService();
// Statement Cglib Method intercept enhanced implementation class
MyCglibProxyMethodInterceptor<ArticleService> cglibProxyMethodInterceptor = new MyCglibProxyMethodInterceptor<>(articleService);
// Get proxy class
ArticleService articleServiceProxy = cglibProxyMethodInterceptor.getProxyObject();
// Use proxy classes to call methods
articleServiceProxy.saveArticle("Java");
}
}
The verification results
A small summary
Simple comparison cglib And JDK A dynamic proxy :
- Use here cglib When acting , Whether or not the target class implements the interface , Can be enhanced .
- But when used alone JDK A dynamic proxy , You can only enhance the methods of class overrides that implement interfaces .
The following is right cglib and JDK Whether dynamic proxy can enhance the comparison code of classes with and without interface implementation , Interested readers can test :
public class MainTest {
public static void main(String[] args) {
cglibProxyNoInterfaceTest();
}
/** * cglib agent ( Proxy target class does not implement interface ) */
private static void cglibProxyNoInterfaceTest(){
ArticleService articleService = new ArticleService();
// Statement Cglib Method intercept enhanced implementation class
MyCglibProxyMethodInterceptor<ArticleService> cglibProxyMethodInterceptor = new MyCglibProxyMethodInterceptor<>(articleService);
// Get proxy class
ArticleService articleServiceProxy = cglibProxyMethodInterceptor.getProxyObject();
// Use proxy classes to call methods
articleServiceProxy.saveArticle("Java");
}
/** * cglib agent ( The proxy target class implements the interface ) */
private static void cglibProxyHasInterfaceTest(){
UserService userService = new UserServiceImpl();
// Statement Cglib Method intercept enhanced implementation class
MyCglibProxyMethodInterceptor<UserService> cglibProxyMethodInterceptor = new MyCglibProxyMethodInterceptor<>(userService);
// Get proxy class
UserService userServiceProxy = cglibProxyMethodInterceptor.getProxyObject();
// Use proxy classes to call methods
userServiceProxy.add("Ara");
}
/** * JDK A dynamic proxy ( The proxy target class implements the interface ) */
private static void jdkDynamicProxyHasInterfaceTest(){
// The original object ( Interface receive parameters )
UserService userService = new UserServiceImpl();
// Declare enhanced handlers
MyJdkProxyInvocationHandler<UserService> proxyInvocationHandler = new MyJdkProxyInvocationHandler<>(userService);
// Get proxy object
UserService proxyUserService = proxyInvocationHandler.getProxyObject();
// Use proxy objects to call methods
proxyUserService.add("Ara");
}
/** * JDK A dynamic proxy ( Proxy target class does not implement interface ) * Mistake , Use JDK Dynamic proxy implementation enhancements , The proxy target must be required to implement the interface */
private static void jdkDynamicProxyNoInterfaceTest(){
ArticleService articleService = new ArticleService();
// Declare enhanced handlers
MyJdkProxyInvocationHandler<ArticleService> proxyInvocationHandler = new MyJdkProxyInvocationHandler<>(articleService);
// Get proxy object
ArticleService proxyArticleService = proxyInvocationHandler.getProxyObject();
// Use proxy objects to call methods
proxyArticleService.saveArticle("Java");
}
}
边栏推荐
- 代码技巧——Controller参数注解@RequestParam
- 日期时间API详解
- Web components series (VIII) -- custom component style settings
- Sudo right raising
- Learn about various joins in SQL and their differences
- The Chinese word segmentation task is realized by using traditional methods (n-gram, HMM, etc.), neural network methods (CNN, LSTM, etc.) and pre training methods (Bert, etc.)
- 浅谈三点建议为所有已经毕业和终将毕业的同学
- CUDA中的Warp matrix functions
- LeetCode 283. 移动零
- 深入学习JVM底层(三):垃圾回收器与内存分配策略
猜你喜欢
网络相关知识(硬件工程师)
Redis——大Key问题
数据科学【八】:SVD(一)
In depth understanding of JUC concurrency (II) concurrency theory
LeetCode 90. Subset II
谷歌出海创业加速器报名倒计时 3 天,创业人闯关指南提前收藏!
State machine in BGP
Invalid operation: Load into table ‘sources_orderdata‘ failed. Check ‘stl_load_errors‘ system table
Contest3147 - game 38 of 2021 Freshmen's personal training match_ G: Flower bed
Linked list (linear structure)
随机推荐
CUDA中的Warp Shuffle
Redis——Cluster数据分布算法&哈希槽
分布式事务 :可靠消息最终一致性方案
New version of dedecms collection and release plug-in tutorial tool
CUDA中的Warp matrix functions
Ros2 --- lifecycle node summary
Is there a really free applet?
利用传统方法(N-gram,HMM等)、神经网络方法(CNN,LSTM等)和预训练方法(Bert等)的中文分词任务实现
Flutter hybrid development: develop a simple quick start framework | developers say · dtalk
LeetCode 27. 移除元素
sudo提权
Linear DP (split)
利用NVIDIA GPU将Minecraft场景渲染成真实场景
锐捷EBGP 配置案例
RestTemplate请求时设置请求头,请求参数,请求体。
亚马逊aws数据湖工作之坑1
IDEA公布全新默认UI,太清爽了(内含申请链接)
Golang--map扩容机制(含源码)
ROS create workspace
【每日一题】—华为机试01