I would like to set three common attributes on my model for each @RequestMapping
within the many controllers in a Spring Boot application. I have read about @ModelAttribute
but it needs to be placed within each Controller. I have more than 20 controllers in my application and each having more than 10 @RequestMapping
.
Is there a way to set such model attributes in one place which gets initialized at the start of the application?
I provide another method by SpringMVC,using the HandlerInterceptor,when you implements it,it provides 3 methods,each of them contains HttpServletRequest,you can set attribute using
request.setAttribute("xx","yy")
,below are the code:then,you need to add the custom interceptor to your spring mvc application like below:
If you want to execute some code on Spring Boot startup, consider this:
Spring boot startup listener
But I guess that you really want Controller related behavior, I would recommend using a Global Interceptor.
With global interceptor, you can interfere with the request-response lifecycle in Spring.
It lets you add functionality to request-response life cycle in 3 different points:
Just create a class which extends from
HandlerInterceptorAdapter
and override one of three methods, with your desired functionality.For Example:
Here's an example on how to do it with Spring Boot: