当前位置:网站首页>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");
}
}
边栏推荐
- 注解和反射详解以及运用
- ROS create workspace
- The official zero foundation introduction jetpack compose Chinese course is coming!
- Compte à rebours de 3 jours pour l'inscription à l'accélérateur de démarrage Google Sea, Guide de démarrage collecté à l'avance!
- LeetCode 77. combination
- 深入学习JVM底层(四):类文件结构
- 浏览器原理思维导图
- Find the highest value of the current element Z-index of the page
- MySQL的10大经典错误
- 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.)
猜你喜欢
随机推荐
阿里云MFA绑定Chrome浏览器
Ros2 --- lifecycle node summary
深入学习JVM底层(五):类加载机制
IDEA公布全新默认UI,太清爽了(内含申请链接)
Bgp Routing preference Rules and notice Principles
Community theory | kotlin flow's principle and design philosophy
BGP中的状态机
利用NVIDIA GPU将Minecraft场景渲染成真实场景
TensorRT的命令行程序
标签属性disabled selected checked等布尔类型赋值不生效?
CUDA用户对象
TensorRT的功能
Data playback partner rviz+plotjuggler
Codeforces Round #797 (Div. 3) A—E
10 erreurs classiques de MySQL
RestTemplate请求时设置请求头,请求参数,请求体。
Contest3145 - the 37th game of 2021 freshman individual training match_ H: Eat fish
Eco express micro engine system has supported one click deployment to cloud hosting
Monitoring uplink of VRRP
On Web server