too many public methods with @ModelAttribute

394 views Asked by At

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?

3

There are 3 answers

1
skaffman On

I have a controller that is 1600 lines long

Gulp.

How do you handle multiple public methods with @ModelAttribute annotation? Aren't they all invoked whenever a request is processed?

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 the Model or ModelMap 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.

0
adarshr On

Can't you group multiple @ModelAttributes together? For example, if you have three methods one each for retrieving the values of three different select boxes, you could perhaps put them all into one method.

0
Rossen Stoyanchev On

@ModelAttribute methods can also return void:

@ModelAttribute
public void populateModel(Model model) {
    model.addAttribute("key", "value");
    // keep adding any number of attributes...
}