liveBook · Manning

@Order annotation

As explained in Spring Start Here, Second Edition

The @Order annotation assigns an execution precedence to components whose ordering affects how they are processed.

When multiple Spring AOP aspects intercept the same method, their order can affect what happens—for example, whether logging captures calls blocked by security. Spring does not guarantee an order by default. Add @Order to an aspect class and give it an ordinal: the smaller the number, the earlier the aspect runs. Equal values leave the order undefined. section 6.3

Ordering security and logging

For aspects intercepting CommentService.publishComment(), @Order(1) on SecurityAspect and @Order(2) on LoggingAspect makes security run first. The execution then passes through logging to the method and returns through logging before security. section 6.3

Figure 6.14 The aspect execution order matters. Depending on your app’s requirements, you need to choose a specific order for the aspects to execute. In this scenario, the LoggingAspect cannot log all the method executions if the SecurityAspect executes first.

See why aspect order matters when security prevents a call from reaching later aspects. section 6.3

How Spring Start Here, Second Edition covers it

How deep it goes
Explains ordinal values and precedence; equal values remain unordered, and default ordering is not guaranteed.
Examples
Uses SecurityAspect and LoggingAspect intercepting CommentService.publishComment() to demonstrate ordering.
What it assumes
Assumes familiarity with Spring AOP aspects and interception; does not establish those concepts here.
What you can do after
Configure aspect precedence by assigning ordinal values with @Order.
How it connects
Connects Spring AOP aspects with method interception and execution chains.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.