Search code examples
javaspringaop

What happens if there are multiple beans having the same @Order value


I have two @ControllerAdvice classes. One is in the application level, the other one is in a dependency. Both @ControllerAdvice has @Order(Ordered.HIGHEST_PRECEDENCE) annotation. Which bean will be picked up (first) for creation?

Controller advice inside application:

package com.package.one.errors

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ControllerAdvice1 {}

Controller advice from dependency:

package com.package.two.errors

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ControllerAdvice2 {}

The ControllerAdvice1 is being used when I run the Spring Boot application. I suspect this has something to do with what beans are encountered first when scanning since the class with @SpringBootApplication is inside the same package as ControllerAdvice1. I would like to know the rules how Spring resolve this.


Solution

  • From the API reference : Ordered.getOrder()

    Same order values will result in arbitrary sort positions for the affected objects

    also

    The actual order can be interpreted as prioritization, with the first object (with the lowest order value) having the highest priority.