In the previous lesson, you learned about the meaning of AOP, and why it's so useful. Now, it's your first opportunity to get your hands dirty with a Spring AOP example!
In this lesson you will learn how to use AOP in your Spring projects. You will discover how Aspects and Pointcuts are defined and how they interact with each other.
Example Location:com.codingnomads.aspectorientedprogramming.aop
AOP in Practice
To help gain a deeper understanding of AOP and how to use it, it's time to see it in action. You will be using the Spring AOP framework, the most widely used and supported framework among the available options.
To enable AOP features in your Spring Boot application, you need to define a Configuration class as the following:
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
}
In the code above,
-
@Configuration: You've encountered this before. As a refresher, this annotation tells Spring that the class defines one or more bean definitions. It is then processed by the Spring container to generate beans at runtime. -
@EnableAspectJAutoProxy: This annotation informs Spring that you plan to use AOP in your codebase, and then Spring does the magic behind the scenes!
This is all it takes to enable AOP features in your Spring Application, now you can start utilizing the power of AOP.
Spring AOP Example Project
Assume you have a simple Student class. Next, you have a StudentService class that communicates with StudentRepository to fetch Student data. It's a pretty standard scenario.
Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
@Table(name = "students")
@ToString
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
}
Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
Service
// this class is service class with business logic
@Service
@RequiredArgsConstructor
public class StudentService {
// inject StudentRepository using constructor injection
private final StudentRepository studentRepository;
public List<Student> fetchAllStudents() {
return studentRepository.findAll();
}
public Student saveStudent(Student student) {
return studentRepository.save(student);
}
public List<Student> saveAllStudents(List<Student> students) {
return studentRepository.saveAll(students);
}
}
Bootstrapping Class
@SpringBootApplication
@RequiredArgsConstructor
public class AOPDemo implements CommandLineRunner {
private final StudentService studentService;
public static void main(String[] args) {
SpringApplication.run(AOPDemo.class);
}
@Override
public void run(String... args) throws Exception {
studentService.saveAllStudents(Arrays.asList(
Student.builder()
.email("student1@example.com")
.name("student1")
.build(),
Student.builder()
.email("student2@example.com")
.name("student2")
.build(),
Student.builder()
.email("student3@example.com")
.name("student3")
.build()
));
studentService.fetchAllStudents();
}
}
Straightforward, standard stuff so far, right? Nothing you haven't seen before.
Implementation of Advice
Assume you would like to perform some logging before the fetchAllStudents() method in your StudentService class is called. The rule of thumb here is when you want to intercept any method prior to its execution, you should use the @Before advice.
@Aspect
@Component
public class ServiceAspect {
@Before("execution(* com.codingnomads." +
"aspectorientedprogramming.aop.service." +
"StudentService.fetchAllStudents())")
public void logFetchAllStudentMethod(JoinPoint joinPoint) {
// write any custom logic according to business requirement
LOGGER.info("Before the execution of : " + joinPoint.getSignature());
}
}
In the code above:
@Aspect: declares this class as an Aspect.@Component: signals the Spring IoC to create and manage this ServiceAspect bean.@Before: takes a pointcut expression like so:execution(* PACKAGE.*.*(..)).
In this case, since you want the advice to only apply to a specific method fetchAllStudents(), you are explicitly defining that you only care about it and not the other methods in the StudentService class. When you run this, it will produce following output:
To optimize this further, you can split the method above by defining a Pointcut method which you can reference in the advice annotation. This is a clean way to avoid duplication of pointcut expressions.
// define a pointcut expression that can be
// referenced from multiple locations
@Pointcut(value =
"execution(* com.codingnomads." +
"aspectorientedprogramming.aop.service.StudentService.*(..))")
private void pointCutAllStudentServiceMethods() {
}
// refer to Pointcut defined above
@Before("pointCutAllStudentServiceMethods()")
public void logBeforeAdvice(JoinPoint joinPoint) {
LOGGER.info("Before Advice : " + joinPoint.getSignature().getName());
}
In the code above,
-
pointCutAllStudentServiceMethods()is annotated with the@PointCutannotation which defines the join point. In this case, the expression is targeting all methods of StudentService class. -
logBeforeAdvice()is an Advice annotated with@Before, referencing thepointCutAllStudentServiceMethods()method.
The code above will produce the following output:
Another annotation is @After. This advice intercepts methods right after the execution of the method.
@After("logAllStudentServiceMethods()")
public void logAfterAdvice(JoinPoint joinPoint) {
System.out.println("After Advice: " +
joinPoint.getSignature().getName());
}
Similarly, the @AfterReturning advice intercepts the method call when the method is executed and returns a result. You can implement logic based on the returned object.
@AfterReturning(
value = "logAllStudentServiceMethods()",
returning = "students")
public void afterReturningAdvice(JoinPoint jp, Object students) {
LOGGER.info("After Returning Advice: Method Name: " +
jp.getSignature().getName());
LOGGER.info("Result: " + students);
}
If you run the application with the code above, it will produce the following output:
Your Turn
Learn by Doing
Package: com.codingnomads.aspectorientedprogramming.aop
- Please navigate to the example package and carefully explore each class defined in this lesson.
- Run the example, and examine the logger output produced when each method is called.
- Inside ServiceAspect, add
@Beforeand@Afteradvice for theStudentService.saveStudent()method. - Now, utilize
saveStudent()a few times in AOPDemo to verify your advice functionality.
Great work! Push your work to GitHub when you're done.
Summary: Spring AOP Example
In this lesson, you explored a few examples to better understand how to use AOP within your Spring application. The general idea is that you define Aspects, which contain Advice (action to be taken), along with Pointcuts (where to apply).