If we start the app and hit the controller endpoint, after login, we would see the user’s email:

Probably you would need to user similar Spring Security Code in almost every controller. Most of the time the domain classes will be associated to a user and you need to know who is logged in. Adding the same code over and over is a bad smell.

If you never used Traits you will probably think about a creating an abstract class and make your controllers inherit from it. Fortunately Groovy Traits offer a much better way to encapsulate this functionality. Lets create a Trait to encapsulate the Spring Security Core Functionality.

If you run the app and hit http://localhost:8080/whoAmI you will get the email back as before.

Note: In previous versions of Grails I had to move the Traits files with the @Enhances annotation to a grails plugin and reference the plugin from the main project. It did not work if you have enhanced classes in the main project.

Do you like to read about Groovy/Grails development? Yes, then Subscribe to Groovy Calamari a weekly curated email newsletter about the Groovy ecosystem which I write