Spring @EnableAspectJAutoProxy Example

By Arvind Rai, 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> 
AppConfig.java
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();
  }
} 
UserAspect.java
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.");
   }
} 
UserService.java
package com.concretepage;
public class UserService {
  public void read() {
    System.out.println("I am reading Ramayan");
  }
} 
SpringDemo.java
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();
	}
} 
Output
My advice before execution.
I am reading Ramayan 

Reference

Spring @EnableAspectJAutoProxy

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us