Home >Java >javaTutorial >How to apply java proxy mode

How to apply java proxy mode

WBOY
WBOYforward
2023-05-06 12:52:061109browse

1. Introduction to the agency model

The agency model is actually to find a substitute. If you want to do something, if you don’t do it yourself, find someone to do it for you. This is the agency model. In the program, a substitute is provided for the object, and the substitute is controlled to access the target object. The advantage of this is that in addition to the functions provided by the target object, the substitute can also do more work, that is, the functions of the target object can be expanded. The proxy can be a remote object, an object that is expensive to create, or an object that requires security control.

The proxy mode is mainly divided into the following three types:

  • Static proxy

  • ##Dynamic proxy (also called JDK proxy, interface Agent)

  • cglib agent (also belongs to the category of dynamic agent)

2. Static agent

 1. Introduction to static proxy: "

When using static proxy, you need to define an interface or parent class. The proxy object and the proxy object need to implement the same interface or inherit the same parent class.

『2. Application example:』

  • Define an interface:

    TeacherDao

  • Define the proxy object:

    TeacherDaoImpl, needs to be implemented TeacherDao

  • Define proxy object:

    TeacherDaoProxy also needs to be implemented TeacherDao

  • To call

    TeacherDaoImpl method, you need to create it first TeacherDaoProxy object, and then create TeacherDaoImpl object, will TeacherDaoImplObject handed over TeacherDaoProxy object, and then call the relevant methods

Code implementation:
  • TeacherDao.java:

<code>public interface TeacherDao {<br>    void teach();<br>}<br></code>
  • TeacherDaoImpl.java:

<code>public class TeacherDaoImpl implements TeacherDao {<br>    @Override<br>    public void teach() {<br>        System.out.println("今天又是没妹子的一天(ノへ ̄、)");<br>    }<br>}<br></code>
  • TeacherDaoProxy.java:

<code>public class TeacherDaoProxy implements TeacherDao {<br>    <br>    private TeacherDao target; // 被代理的对象<br>    <br>    public TeacherDaoProxy(TeacherDao target){<br>        this.target = target;<br>    }<br>    <br>    @Override<br>    public void teach() {<br>        System.out.println("代理开始");<br>        // 这里可以写一些额外的逻辑,以达到扩展被代理对象的目的,相当于spring的前置通知<br>        target.teach();<br>        // 这里也可以写一些额外的逻辑,以达到扩展被代理对象的目的,相当于spring的后置通知<br>        System.out.println("代理结束");<br>    }<br>}<br></code>
  • Client.java: Call the proxy object

<code>public class Client {<br><br>    public static void main(String[] args){<br>        // 创建被代理的对象<br>        TeacherDao target = new TeacherDaoImpl();<br>        // 创建代理对象<br>        TeacherDaoProxy proxy = new TeacherDaoProxy(target);<br>        // 通过代理对象调用方法<br>        proxy.teach();<br>    }<br>}<br></code>

『3. Advantages and disadvantages of static proxy:』

  • Advantages: The proxy object can be extended without modifying the proxy object. Some enhancements

  • Disadvantages: Need to implement the same interface or inherit the same parent class, so there will be many proxy classes, and if the interface or parent class is changed, the proxy object and the proxy object will both Maintenance required

3. Dynamic proxy (JDK proxy)

「1. Dynamic proxy introduction:」

Proxy object Do not implement the interface, but the proxy object still needs to implement the interface. The generation of dynamic proxy objects uses the JDK API and the Proxy class under the reflection package to dynamically build proxy objects in memory.

『2.java.lang.reflect.Proxy:』

This class has a

newProxyInstance method, which receives three parameters, As follows:

<code>static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)<br></code>

『3. Application example:』

  • Define an interface: TeacherDao

  • Define the proxy object : TeacherDaoImpl, you need to implement TeacherDao

  • Define a proxy factory ProxyFactory, there is a getProxyInstance method, you need to pass in the proxy object, and then return the proxy object instance, and call the proxy object through the proxy object Method

Code implementation:
  • TeacherDao.java:

<code>public interface TeacherDao {<br>    void teach();<br>}<br></code>
  • TeacherDaoImpl.java:

<code>public class TeacherDaoImpl implements TeacherDao {<br>    @Override<br>    public void teach() {<br>        System.out.println("今天又是没妹子的一天(ノへ ̄、)");<br>    }<br>}<br></code>
  • ProxyFactory.java

<code>public class ProxyFactory {<br><br>    private Object target; // 被代理的对象<br><br>    public ProxyFactory(Object target){<br>        this.target = target;<br>    }<br><br>    // 给被代理的对象生成一个代理对象<br>    public Object getProxyInstance(){<br>        // 参数1:指定被代理对象的类加载器<br>        // 参数2:被代理对象实现的接口类型<br>        // 参数3:事件处理,执行被代理对象的方法<br>        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {<br>            @Override<br>            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {<br>                System.out.println("JDK代理开始");<br>                // 调用方法,args的方法的参数<br>                Object returnValue = method.invoke(target, args);<br>                System.out.println("JDK代理结束");<br>                // 将执行结果return<br>                return returnValue;<br>            }<br>        });<br>    }<br>}<br></code>
  • Client.java: Calling method through proxy

<code>public class Client {<br><br>    public static void main(String[] args){<br>        // 创建被代理的对象<br>        TeacherDao target = new TeacherDaoImpl();<br>        // 创建代理对象<br>        TeacherDao proxy = (TeacherDao) new ProxyFactory(target).getProxyInstance();<br>        // 通过代理对象调用被代理对象的方法<br>        proxy.teach();<br>    }<br>}</code>  
  
4. cglib proxy

「1. Introduction to cglib proxy: 』

Static proxy and dynamic proxy, the proxied object needs to implement the interface. If a class does not implement any interface, then cglib proxy must be used. The cglib agent is also called a subclass agent. It builds a subclass object in memory to extend the proxy object. The bottom layer of the cglib agent uses a bytecode processing framework called ASM to convert bytecode and generate new classes to implement the agent. The proxied class cannot be final, otherwise an error will be reported. If the method of the proxy object is final/static, it will not be intercepted, that is, no additional business methods of the proxy object will be executed.

『2. Application examples:』

  • 首先要添加cglib相关依赖:

<code><dependency><br>     <groupId>cglib</groupId><br>     <artifactId>cglib</artifactId><br>     <version>3.3.0</version><br></dependency><br></code>
 
  • TeacherDaoImpl.java:

<code>public class TeacherDaoImpl implements TeacherDao {<br>    @Override<br>    public void teach() {<br>        System.out.println("今天又是没妹子的一天(ノへ ̄、)");<br>    }<br>}<br></code>
 
  • CglibProxyFactory.java:

<code>// 需要实现MethodInterceptor并重写其方法<br>public class CglibProxyFactory implements MethodInterceptor {<br><br>    private Object target;<br><br>    public CglibProxyFactory(Object target){<br>        this.target = target;<br>    }<br><br>    /**<br>     * 返回target的代理对象<br>     * @return<br>     */<br>    public Object getProxyInstance(){<br>        // 1. 创建工具类<br>        Enhancer enhancer = new Enhancer();<br>        // 2. 设置父类<br>        enhancer.setSuperclass(target.getClass());<br>        // 3. 设置回调函数<br>        enhancer.setCallback(this);<br>        // 4. 创建子类对象,即代理对象<br>        return enhancer.create();<br>    }<br>    @Override<br>    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {<br>        System.out.println("CGLIB代理开始");<br>        Object returnValue = method.invoke(target, args);<br>        System.out.println("CGLIB代理结束");<br>        return returnValue;<br>    }<br>}<br></code>
 
  • Client.java:通过代理调用方法

<code>public class Client {<br><br>    public static void main(String[] args){<br>        // 创建被代理的对象<br>        TeacherDaoImpl target = new TeacherDaoImpl();<br>        // 获取代理对象,并将被代理对象传给代理对象<br>        TeacherDaoImpl proxy = (TeacherDaoImpl) new CglibProxyFactory(target).getProxyInstance();<br>        // 执行方法,触发intecept方法,从而实现执行被代理对象的方法<br>        proxy.teach();<br>    }<br>}<br></code>

The above is the detailed content of How to apply java proxy mode. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete