简体   繁体   中英

why spring AOP use JDK Dynamic proxy?

I know Spring AOP use JDK dynamic proxy and CGLIB.

when target implents Interface -> JDK dynamic proxy

else -> CGLIB.

As you can see why there was this reason in the past version, CGLIB currently has all its shortcomings secured, and in terms of performance, it is superior to the JDK method.

Why would you still use the JDK for the target that implements the interface though? Making all the targets CGLIB seems to have more advantages.

Converting my comments into an answer...

User RG said:

This SO Q&A provides a lot of insights on the topic.

The accepted answer is not very helpful, but Rafael's comment under his own answer explains it: "Cglib is an external dependeny (...) Relying on third-party software is always a gamble, so it is best when as few people as possible rely on it." Ie, if you have a Spring application with very clean design, always programming against interfaces instead of directly against classes, you do not need CGLIB at all.

Slightly off-topic, but FYI: For similar reasons, the Spock testing framework supports JDK interface proxies out of the box for users who only need interface mocks. In that case, the optional dependency CGLIB (or ByteBuddy) and special stuff like Objenesis are unnecessary. So, this kind of strategy is quite common.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM