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");
}
}
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.
Cglib is used extensively by the Spring framework.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With