Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-Boot 2+ forces CGLIB proxy even with proxyTargetClass = false

The proxification setup seems to have changed between Spring-Boot 1.5+ and 2.+.

In Spring 1.5.20 with @EnableAspectJAutoProxy(proxyTargetClass = false) or just @EnableAspectJAutoProxy or even no annotation @EnableAspectJAutoProxy I would get a JdkDynamicAopProxy. And with @EnableAspectJAutoProxy(proxyTargetClass = true) I would get CGLIB enhanced classes. OK all good.

With the same code with Spring 2.1.4, I get a CGLIB enhanced ServiceImpl all the time whatever the config.

I did not managed to have JdkDynamicAopProxy proxies with Spring 2+.

Is there still a way to do it ?

Here is my code:

@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass = false)
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
        MyService service = context.getBean(MyService.class);
        service.execute();
    }
}


@Aspect
@Component
public class ChronoAspect {
    @Around("execution(* com.example.demo.service..*.*(..))")
    public Object chronoAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        // .....
    }

}

public interface MyService {
    void execute();
}

@Component
public class ServiceImpl implements MyService {
    public void execute() {
        System.out.println("Hello execute from Service.execute");
    }
}
like image 960
Gauthier Peel Avatar asked Apr 25 '19 15:04

Gauthier Peel


People also ask

How are JDK dynamic proxies and Cglib proxies used in spring?

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.

Does spring use Cglib?

Cglib is used extensively by the Spring framework.

What is proxy target class true?

proxy-target-class is an attribute of the AOP config that, if set to “true” forces the proxying to use CGLIB proxies instead of Java Proxies. Null Pointer Exception (NPE) is the bane of any software engineer that occurs when a reference to an object contains a NULL value.

How does Cglib proxy work?

Cglib and Javassist provide support for proxying classes because they can dynamically generate bytecode (i.e. class files), allowing us to extend classes at runtime in a way that Java's Proxy can implement an interface at runtime. At the core of Cglib is the Enhancer class, which is used to generate dynamic subclasses.


1 Answers

It's a known issue.

Currently you can only set

spring.aop.proxy-target-class=false

in your config file to force it to use JDKProxy.

like image 146
AwesomeHunter Avatar answered Oct 02 '22 07:10

AwesomeHunter