当前位置:网站首页>Cglib agent in agent mode

Cglib agent in agent mode

2022-07-07 02:50:00 Xiaobai without work

1:CGLIB Agency features

cglib It's about classes that implement proxies
Its principle is to generate a subclass of the specified target class , And cover the methods to realize the enhancement
Because it's inheritance , So we can't be right final Decorated class to proxy

2: Code implementation

2.1: stay pom.xml Introduce in the file cglib Related dependence of

<!-- https://mvnrepository.com/artifact/cglib/cglib --> 
<dependency> 
	<groupId>cglib</groupId> 
	<artifactId>cglib</artifactId> 
	<version>2.2.2</version> 
</dependency>

2.2: Define the target class

// You don't need to write a parent class or implement an interface 
public class Me {
    
    public void show(){
    
        System.out.println(" I did ");
    }
}

2.3: Define proxy class , Implementation interface

/* cglib A dynamic proxy  */
public class CglibInterceptor implements MethodInterceptor {
    
    //  Target audience 
    private Object target;
    //  Pass in the target object through the constructor 
    public CglibInterceptor(Object target) {
    
        this.target = target;
    }
    /***  Interceptor  * 1、 Method call of target object  * 2、 Reinforcement behavior  * @param o  from CGLib Dynamically generated proxy class instances  * @param method  The proxy method reference called by the entity class  * @param objects  Parameter value list  * @param methodProxy  The proxy reference of the generated proxy class to the method  * @return * @throws Throwable */
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
    
        System.out.println(" Before method execution ...");
        Object result = methodProxy.invoke(target, objects);
        System.out.println(" After method execution ...");
        return result;
    }
    public Object getProxy(){
    
        //  adopt Enhancer Object's create() Method can generate a class , Used to generate proxy objects 
        Enhancer enhancer = new Enhancer();
        //  Set parent class  ( No parent class has the target class as its parent )
        enhancer.setSuperclass(target.getClass());
        // Set up interceptors   The callback object is its own object 
        enhancer.setCallback(this);
        //  Generate a proxy class object , And back to 
        return enhancer.create();
    }
}

2.4: Code testing

public class Test {
    
    public static void main(String[] args) {
    
        Me me = new Me();
        CglibInterceptor cglib02 = new CglibInterceptor(me);
        Me u = (Me) cglib02.getProxy();
        u.show();
    }
}
原网站

版权声明
本文为[Xiaobai without work]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130857397454.html