Search code examples
spring-bootaopspring-aop

What is the correct package hierarchy for @Aspect classes and @ControllerAdvice classes?


Problem Details
I`m currently implementing two classes in my Spring Boot, Spring MVC project.

First:

@ControllerAdvice
class GlobalDefaultExceptionHandler {
// body not relevant to this problem
}

Second:

@Aspect
@Component
public class MyAspect {
// body not relevant to this problem
}

The current project package hierarchy looks like this. Hierarchy:

com.example
├── aspect
│   └── MyAspect.java
├── advice
│   └── GlobalDefaultExceptionHandler.java

Problem
I`m not sure if this is the correct package hierarchy.

Possible Solution
Since both advice and aspect are Spring AOP features, should I place these two packages in one base package called 'aop'?

A possible solution for my project package hierarchy. Hierarchy:

com.example
└── aop
    ├── aspect
    │   └── MyAspect.java
    │
    └── advice
        └── GlobalDefaultExceptionHandler.java

Please, correct me if I`m wrong.


Solution

  • I would suggest sticking to the first approach, where you have a package based on the type of components - Repository/Controller/Service..

    com.example
    ├── aspect
    │   └── MyAspect.java
    ├── advice
    │   └── GlobalDefaultExceptionHandler.java
    

    First, AOP means Aspect-Oriented Programming, noting component related

    Second, If you check Spring ControllerAdvice for the reference, you will notice that it doesn't come from a specific aop related package

    import org.springframework.web.bind.annotation.ControllerAdvice;
    

    When I personally have concerns about such stuff, I always prefer to check Java libraries or some other libraries for the reference