Spring @EnableAspectJAutoProxy Example
February 21, 2022
Spring @EnableAspectJAutoProxy
annotation enables support for handling components marked with @Aspect
annotation of AspectJ. The @EnableAspectJAutoProxy
is used on @Configuration
classes. The @EnableAspectJAutoProxy
is equivalent to <aop:aspectj-autoproxy>
XML element.
Example
Find the dependency for Spring AOP.<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
package com.concretepage; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration @EnableAspectJAutoProxy public class AppConfig { @Bean public UserService userService(){ return new UserService(); } @Bean public UserAspect userAspect(){ return new UserAspect(); } }
package com.concretepage; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class UserAspect { @Before("execution(* com.concretepage.UserService+.*(..))") public void userAdvice(){ System.out.println("My advice before execution."); } }
package com.concretepage; public class UserService { public void read() { System.out.println("I am reading Ramayan"); } }
package com.concretepage; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class SpringDemo { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class); ctx.refresh(); UserService userService= ctx.getBean(UserService.class); userService.read(); } }
My advice before execution. I am reading Ramayan