国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Java Javagetting Started What are the three proxy modes of java?

What are the three proxy modes of java?

Jan 30, 2021 am 09:44 AM
java proxy mode

What are the three proxy modes of java?

First of all, let’s briefly explain what the proxy mode is.

Proxy is a design pattern that provides another way to access the target object; that is, access the target object through the proxy object. The advantage of this is that it can enhance the target object based on the implementation of the target object. Additional functional operations, that is, extending the functions of the target object.
An idea in programming is used here: do not modify the code or methods that have been written by others at will. If you need to modify it, you can extend it through a proxy. Method

Give an example to illustrate the role of an agent: Suppose we want to invite a star, then we do not directly contact the star, but contact the star's agent to achieve the same purpose. The star is a target object , he only needs to be responsible for the program at the event, and other trivial matters are left to his agent (broker) to solve. This is an example of agency thinking in reality.

The diagram is as follows:

What are the three proxy modes of java?

The key points of the proxy mode are: proxy object and target object. The proxy object is an extension of the target object and will call the target object

1.1. Static Proxy

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

The following is a case to explain :
Simulate the save action, define an interface for the save action: IUserDao.java, and then the target object implements the method UserDao.java of this interface. At this time, if you use the static proxy method, you need to in the proxy object (UserDaoProxy.java) Also implements the IUserDao interface. When calling, call the target object by calling the method of the proxy object.
It should be noted that the proxy object and the target object must implement the same interface, and then call the method of the target object by calling the same method.

Code example:
Interface:IUserDao.java

/**
 * 接口
 */public interface IUserDao {    void save();
}

Target object:UserDao.java

/**
 * 接口實現(xiàn)
 * 目標(biāo)對象
 */public class UserDao implements IUserDao {    public void save() {
        System.out.println("----已經(jīng)保存數(shù)據(jù)!----");
    }
}

Proxy object:UserDaoProxy.java

/**
 * 代理對象,靜態(tài)代理
 */public class UserDaoProxy implements IUserDao{    //接收保存目標(biāo)對象
    private IUserDao target;    public UserDaoProxy(IUserDao target){        this.target=target;
    }    public void save() {
        System.out.println("開始事務(wù)...");
        target.save();//執(zhí)行目標(biāo)對象的方法
        System.out.println("提交事務(wù)...");
    }
}

(Learning video sharing: java video tutorial)

Test class:App.java

/**
 * 測試類
 */public class App {    public static void main(String[] args) {        //目標(biāo)對象
        UserDao target = new UserDao();        //代理對象,把目標(biāo)對象傳給代理對象,建立代理關(guān)系
        UserDaoProxy proxy = new UserDaoProxy(target);

        proxy.save();//執(zhí)行的是代理的方法
    }
}

Static agent summary:
1. It can be done without modifying the target Under the premise of the function of the object, the target function is expanded.
2. Disadvantages:

Because the proxy object needs to implement the same interface as the target object, there will be many proxy classes, too many classes. At the same time, once When adding methods to the interface, both the target object and the proxy object must be maintained.

How to solve the shortcomings of static proxy? The answer is that you can use dynamic proxy method

1.2. Dynamic proxy

Dynamic proxy has the following characteristics:
1. Proxy object does not need to implement the interface
2. The generation of proxy object is to use the API of JDK to dynamically build the proxy object in the memory (we need to specify the creation of proxy object /The type of interface implemented by the target object)
3. Dynamic proxy is also called: JDK proxy, interface proxy

API for generating proxy objects in JDK
The package where the proxy class is located: java.lang.reflect .Proxy
JDK only needs to use the newProxyInstance method to implement the proxy, but this method needs to receive three parameters. The complete writing method is:

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

Note that this method is a static method in the Proxy class and receives The three parameters are:

ClassLoader loader,: specifies the current target object to use the class loader, and the method of obtaining the loader is fixed

Class[] interfaces,: target The type of interface implemented by the object, use generics to confirm the type

InvocationHandler h: event processing, when executing the method of the target object, the method of the event processor will be triggered, and the method of the currently executed target object will be used as a parameter Pass in

code example:
interface class IUserDao.java and interface implementation class. The target object UserDao is the same without modification. On this basis, add a proxy factory class (ProxyFactory.java) , write the proxy class in this place, and then first establish the connection between the target object and the proxy object in the test class (the code that needs to use the proxy), and then use the method of the same name in the proxy object

Agent factory class: ProxyFactory.java

/**
 * 創(chuàng)建動態(tài)代理對象
 * 動態(tài)代理不需要實現(xiàn)接口,但是需要指定接口類型
 */public class ProxyFactory{    //維護一個目標(biāo)對象
    private Object target;    public ProxyFactory(Object target){        this.target=target;
    }   //給目標(biāo)對象生成代理對象
    public Object getProxyInstance(){        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),                new InvocationHandler() {                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("開始事務(wù)2");                        //執(zhí)行目標(biāo)對象方法
                        Object returnValue = method.invoke(target, args);
                        System.out.println("提交事務(wù)2");                        return returnValue;
                    }
                }
        );
    }

}

Test class: App.java

/**
 * 測試類
 */public class App {    public static void main(String[] args) {        // 目標(biāo)對象
        IUserDao target = new UserDao();        // 【原始的類型 class cn.itcast.b_dynamic.UserDao】
        System.out.println(target.getClass());        // 給目標(biāo)對象,創(chuàng)建代理對象
        IUserDao proxy = (IUserDao) new ProxyFactory(target).getProxyInstance();        // class $Proxy0   內(nèi)存中動態(tài)生成的代理對象
        System.out.println(proxy.getClass());        // 執(zhí)行方法   【代理對象】
        proxy.save();
    }
}

Summary:
The proxy object does not need to implement the interface, but the target object must implement the interface, otherwise dynamic proxy cannot be used

1.3.Cglib proxy

The above static proxy and dynamic proxy modes require the target object to be a target object that implements an interface, but sometimes the target object is just a separate object and does not implement any interface, at this time you can use the target object subclass to implement the proxy. This method is called: Cglib proxy

Cglib代理,也叫作子類代理,它是在內(nèi)存中構(gòu)建一個子類對象從而實現(xiàn)對目標(biāo)對象功能的擴展.

JDK的動態(tài)代理有一個限制,就是使用動態(tài)代理的對象必須實現(xiàn)一個或多個接口,如果想代理沒有實現(xiàn)接口的類,就可以使用Cglib實現(xiàn).Cglib是一個強大的高性能的代碼生成包,它可以在運行期擴展java類與實現(xiàn)java接口.它廣泛的被許多AOP的框架使用,例如Spring AOP和synaop,為他們提供方法的interception(攔截)Cglib包的底層是通過使用一個小而塊的字節(jié)碼處理框架ASM來轉(zhuǎn)換字節(jié)碼并生成新的類.不鼓勵直接使用ASM,因為它要求你必須對JVM內(nèi)部結(jié)構(gòu)包括class文件的格式和指令集都很熟悉.

Cglib子類代理實現(xiàn)方法:
1.需要引入cglib的jar文件,但是Spring的核心包中已經(jīng)包括了Cglib功能,所以直接引入pring-core-3.2.5.jar即可.
2.引入功能包后,就可以在內(nèi)存中動態(tài)構(gòu)建子類
3.代理的類不能為final,否則報錯
4.目標(biāo)對象的方法如果為final/static,那么就不會被攔截,即不會執(zhí)行目標(biāo)對象額外的業(yè)務(wù)方法.

代碼示例:
目標(biāo)對象類:UserDao.java

/**
 * 目標(biāo)對象,沒有實現(xiàn)任何接口
 */public class UserDao {    public void save() {
        System.out.println("----已經(jīng)保存數(shù)據(jù)!----");
    }
}

Cglib代理工廠:ProxyFactory.java

/**
 * Cglib子類代理工廠
 * 對UserDao在內(nèi)存中動態(tài)構(gòu)建一個子類對象
 */public class ProxyFactory implements MethodInterceptor{    //維護目標(biāo)對象
    private Object target;    public ProxyFactory(Object target) {        this.target = target;
    }    //給目標(biāo)對象創(chuàng)建一個代理對象
    public Object getProxyInstance(){        //1.工具類
        Enhancer en = new Enhancer();        //2.設(shè)置父類
        en.setSuperclass(target.getClass());        //3.設(shè)置回調(diào)函數(shù)
        en.setCallback(this);        //4.創(chuàng)建子類(代理對象)
        return en.create();

    }    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("開始事務(wù)...");        //執(zhí)行目標(biāo)對象的方法
        Object returnValue = method.invoke(target, args);

        System.out.println("提交事務(wù)...");        return returnValue;
    }
}

測試類:

/**
 * 測試類
 */public class App {    @Test
    public void test(){        //目標(biāo)對象
        UserDao target = new UserDao();        //代理對象
        UserDao proxy = (UserDao)new ProxyFactory(target).getProxyInstance();        //執(zhí)行代理對象的方法
        proxy.save();
    }
}

在Spring的AOP編程中:
如果加入容器的目標(biāo)對象有實現(xiàn)接口,用JDK代理
如果目標(biāo)對象沒有實現(xiàn)接口,用Cglib代理

相關(guān)推薦:java入門教程

The above is the detailed content of What are the three proxy modes of java?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1500
276
How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

See all articles