I have a controller that is 1600 lines long. This is mostly populated with a bunch of public methods with the @ModelAttribute
annotation. It also has a few @RequestMapping
methods.
I would like to bring down the line count and break-up this class. How do you handle multiple public methods with @ModelAttribute
annotation? Aren't they all invoked whenever a request is processed?
Gulp.
When used to annotate a method, this annotation indicates that the method's return value should be used to populate the model for every request executed by that controller class, regardless of which
@RequestMapping
method is executed.My suggestion is that you perform an audit to see which views (e.g. JSPs) use which model data provided by the various
@ModelAttribute
methods. It's likely that each view only uses a subset of that data.Once you've figured out which combinations of
@ModelAttribute
and@RequestMapping
methods go together, then break those up into individual classes.If that doesn't fly (maybe all of the views really do use all of the data), then consider extracting the
@ModelAttribute
methods out of the class altogether, and stitch them together using a single method which amalgamates their outputs together manually (e.g. pass theModel
orModelMap
object from the@RequestMapping
method to this new method, which then adds the bits of model to that object.Remember,
@ModelAttribute
-annotated methods are just a convenient way to add extra model data. They're not the only way.