To the best of my knowledge, creating a dynamic Java proxy requires that one have an interface to work against for the proxy. Yet, Hibernate seems to manage its dynamic proxy generation without requiring that one write interfaces for entity classes. How does it do this? The only clue from the Hibernate documentation refers to the fact that classes must have at minimum a package-visible constructor for proxy generation.
Is Hibernate doing runtime bytecode engineering with a custom classloader? The documentation suggests that this is not the case. So how do they create their proxy wrappers around the concrete entity objects? Do they just create a proxy of some trivial interface without concern for type safety and then cast it as desired?
Since Hibernate 3.3, the default bytecode provider is now Javassist rather than CGLib.
Hibernate Core Migration Guide : 3.3
Hibernate uses the bytecode provider configured in hibernate.properties, for example:
hibernate.bytecode.provider=javassist
See class javassist.util.proxy.ProxyFactory for details.
Related
I am doing a mock exam where I didn't quite understand one of the answers which lacked an explanation of why it was correct.
(Edited from here downward by kriegaex, adding the question from the below comment and some formatting and rephrasing in order to make the text a bit more coherent and readable.)
Question: "Which below statement is true about Spring's proxy feature?"
Answer: "There is a type of Spring proxy that can replace the object being returned by the method."
I understand that Spring AOP can use two types of proxies:
JDK dynamic proxies
CGLIB proxies
In my understanding these are the two type of proxies that are heavily used in Spring. For example when using #Transactional or when creating aspects (#Aspect).
What I understand of the answer given is that they are pointing at the #Around aspect. However, I don't understand why they call it a "type of Spring proxy". Is an aspect a proxy? Thus, is my understanding of an aspect making use of the JDK or the CGLIB proxies incorrect?
The question would be easier to understand if you had provided all possible answers, also the incorrect ones. But given the correct one (which really does sound strange), I can tell you the following:
Both JDK and CGLIB proxies serve the same purpose: to wrap and replace the original objects in order to be able to register some interceptors to their method calls, be it via Spring AOP or other methods.
Yes, both proxy types are used heavily in Spring, JDK proxies for classes implementing interfaces, CGLIB proxies for classes not implementing any interfaces. Optionally, you can configure Spring to use CGLIB proxies also for interface types.
There is no such thing as an "#Around aspect", only an #Around advice type (beside other advice types like e.g. #Before and #After).
No, an aspect is not a proxy. But Spring AOP uses proxies in order to implement its way of doing AOP via delegation pattern, as opposed to AspectJ which does not use any proxies but uses direct bytecode instrumentation to achieve its goal.
Find more information in the Spring documentation.
When I was going through spring core related document, I came across concept called "Inheritance based proxies".
Can anyone please explain a bit on this. It will be nice if you can show some
code samples.
Thanks
There are two types of proxies available in Spring:
JDK proxy, which comes out of the box in JDK and CGLib, which is created by the CGLib library (3rd party dependency).
JDK Proxy only works with beans that implement an interface and it is also the Spring recommended way of using AOP.
However, there are lots of scenarios out there where you would have to code concrete classes and therefore must use CGLib. CGLIB proxying works by generating a subclass of the target class at runtime. Spring configures this generated subclass to delegate method calls to the original target: the subclass is used to implement the Decorator pattern, weaving in the advice.
I think that's what is being referred to as 'inheritance based proxy'. http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop-api.html#aop-api-proxying-class
In the question below EVERYBODY
What's the difference between JPA and Hibernate?
told that JPA is specification.It is something abstract without Eclipselink or Hibernate
Is JPA javax.persistence.sth right?
Moreover we can use concrete things like
javax.persistence.EntityManager.persiste
javax.persistence.EntityManager.delete/remove
EDIT
Does eclipselink and hibernate put their own code into these packages, these classes???
JPA is a specification, and a number of implementors provide implementations that follow the specification.
So, if you use JPA as it is meant to be used, you can then choose from one or more of the implementors and it should "plug-and-play" work. In other words, you shouldn't have to change your code, because the implementation will do what the specification promises.
--- As for the difference between JPA and Hibernate ---
JPA is a specification, but Hibernate is an implementation. If you write against JPA you can change between JPA compatible implementations with some ease; but, if you write against Hibernate, to change you effectively need to rewrite your database access code.
Note that Hibernate also provides some JPA compatibility, if you take care to use only the JPA compatible part of Hibernate, you effectively are writing against JPA with Hibernate providing the implementation.
There is a receipe for doing JPA development that works quite well at preventing non-JPA (implementation specific) code from being written.
Find the JPA jar for the version of JPA you are targeting.
Add that jar to the compile class path, and the run time classpath.
Find the JPA provider you wish to use (Hibernate, etc).
Add that / those jars to the run time classpath only.
JPA is Java Persistence API released as a JSR (Java Specification Requests) by JCP (Java Community Process).
It is kind of specification; in other words like interface, no implementation includes.
Every vendor (implementors) who interested this spec needs to implement as it says in specification document.
Here is example JPA 2.0 spec
In case of the Proxy Design Pattern, What is the difference between JDK's Dynamic Proxy and third party dynamic code generation API s such as CGLib?
What is the difference between using both the approaches and when should one prefer one over another?
JDK Dynamic proxy can only proxy by interface (so your target class needs to implement an interface, which is then also implemented by the proxy class).
CGLIB (and javassist) can create a proxy by subclassing. In this scenario the proxy becomes a subclass of the target class. No need for interfaces.
So Java Dynamic proxies can proxy: public class Foo implements iFoo where CGLIB can proxy: public class Foo
EDIT:
I should mention that because javassist and CGLIB use proxy by subclassing, that this is the reason you cannot declare final methods or make the class final when using frameworks that rely on this. That would stop these libraries from allowing to subclass your class and override your methods.
Differences in functionality
The JDK proxies allow to implement any set of interfaces while subclassing Object. Any interface method, plusObject::hashCode, Object::equals and Object::toString is then forwarded to an InvocationHandler. Additionally, the standard library interface java.lang.reflect.Proxy is implemented.
cglib allows you to implement any set of interfaces while subclassing any non-final class. Also, methods can be overridden optionally, i.e. not all non-abstract methods need to be intercepted. Furthermore, there are different ways of implementing a method. It also offers an InvocationHandler class (in a different package), but it also allows to call super methods by using more advanced interceptors as for example a MethodInterceptor. Furthermore, cglib can improve performance by specialized interceptions like FixedValue. I once wrote a summary of different interceptors for cglib.
Performance differences
JDK proxies are implemented rather naively with only one interception dispatcher, the InvocationHandler. This requires a virtual method dispatch to an implementation which cannot always be inlined. Cglib allows to create specialized byte code what can sometimes improve performance. Here are some comparisons for implementing an interface with 18 stub methods:
cglib JDK proxy
creation 804.000 (1.899) 973.650 (1.624)
invocation 0.002 (0.000) 0.005 (0.000)
The time is noted in nanoseconds with standard deviation in braces. You can find more details on the benchmark in Byte Buddy's tutorial, where Byte Buddy is a more modern alternative to cglib. Also, note that cglib is no longer under active development.
Dynamic proxy: Dynamic implementations of interfaces at runtime using JDK Reflection API.
Example: Spring uses dynamic proxies for transactions as follows:
The generated proxy comes on top of bean. It adds transnational behavior to the bean. Here the proxy generates dynamically at runtime using JDK Reflection API.
When an application is stopped, the proxy will be destroyed and we will only have interface and bean on the file system.
In the above example we have interface. But in most of implementation of interface is not best. So bean does not implement an interface, in that case we uses inheritance:
In order to generate such proxies, Spring uses a third party library called CGLib.
CGLib (Code Generation Library) is built on top of ASM, this is mainly used the generate proxy extending bean and adds bean behavior in the proxy methods.
Examples for JDK Dynamic proxy and CGLib
Spring ref
From Spring documentation :
Spring AOP uses either JDK dynamic proxies or CGLIB to create the
proxy for a given target object. (JDK dynamic proxies are preferred
whenever you have a choice).
If the target object to be proxied implements at least one interface
then a JDK dynamic proxy will be used. All of the interfaces
implemented by the target type will be proxied. If the target object
does not implement any interfaces then a CGLIB proxy will be created.
If you want to force the use of CGLIB proxying (for example, to proxy
every method defined for the target object, not just those implemented
by its interfaces) you can do so. However, there are some issues to
consider:
final methods cannot be advised, as they cannot be overriden.
You will need the CGLIB 2 binaries on your classpath, whereas dynamic
proxies are available with the JDK. Spring will automatically warn you
when it needs CGLIB and the CGLIB library classes are not found on the
classpath.
The constructor of your proxied object will be called twice. This is a
natural consequence of the CGLIB proxy model whereby a subclass is
generated for each proxied object. For each proxied instance, two
objects are created: the actual proxied object and an instance of the
subclass that implements the advice. This behavior is not exhibited
when using JDK proxies. Usually, calling the constructor of the
proxied type twice, is not an issue, as there are usually only
assignments taking place and no real logic is implemented in the
constructor.
I know that Javassist is a Java library providing a means to manipulate the Java bytecode of an application.
Ok, but why we need manipulate bytecode?
Any real example?
Any real app, where javassist used?
A common application is to generate proxy classes at runtime, i.e. to create a subclass at runtime that intercepts all method invocations. Examples:
Hibernate uses Proxies to intercept method invocations on entities to implement lazy loading, i.e. fetching the object from the database when it is first accessed.
The Spring Framework uses Proxies to implement its AOP support, which among other things powers its support for declarative transactions. It also uses proxies to enforce proper scoping.
EJB uses proxies to implement container managed transactions, authorization checking, and to apply user-defined interceptors.
CDI implementations must also proxy the managed beans to ensure proper scoping. I suspect they use a byte code engineering library, too.
I recently used Javassist to implement a transparent cache for method return values, by intercepting all method invocations and only delegating to the super implementation on the first invocation.
Note that java.lang.reflect.Proxy can generate proxy classes at runtime, but can only implement interfaces, not extend a class. All of the above use cases require the proxying of classes.
Bytecode manipulation is useful and necessary, especially when you do not have source code for certain projects. Say you only have the bytecode (like a jar file) for some project, but you want somehow change the behavior of the code, the bytecode manipulation library can help in such cases. The advantage of bytecode manipulation is that you don't need to recompile your code and can directly execute it after manipulation.
I have used bytecode manipulation to do some program analysis. Given a library, I want to know during the runtime what methods in the library have been invoked. I can use bytecode manipulation to insert a System.out.println("method_name"); statement in the beginning of a method. So during the runtime, it will print out what methods have been invoked.
Some bytecode manipulation libraries are:
ASM
ByteBuddy
BCEL
To extend Meriton answer and to provide a real example of use :
Hibernate-core (5.2.8.Final) use javaassit (3.20.0-GA):
https://mvnrepository.com/artifact/org.hibernate/hibernate-core/5.2.8.Final
Users page of the ASM project lists several dozen widely used Java projects and frameworks using ASM for bytecode analysis and manipulation. http://asm.ow2.org/users.html