Search code examples
springcglib

Why does Spring inject some of my dependencies as CGLIB proxies and why are the attributes null?


I have a @Service that has 4 classes @Autowired. 2 of them appear to be concrete classes, but the other 2 are EnhancedBySpringCGLIB.

enter image description here

The 2 that are CGLIB proxied both have some methods with annotations, such as @Transactional, @Async, @Scheduled, is this why they are proxied in this way?

Why are the attributes on these beans all null? I can put a breakpoint into those classes and see them populated on startup, but by the time they are injected into my service they are blank.

I have checked ApplicationContext, there is only 1 bean created.

I'm using spring boot 2.4.2


Solution

  • Concerning the usage of CGLIB proxies:

    "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."

    From https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch08s06.html

    Concerning why the fields in the proxy are null:

    In CGLIB proxies, the constructor for the parent class is not invoked. You can find a good explanation here:

    spring singleton bean fields are not populated