简体   繁体   English

Spring MVC:模型中的属性过多

[英]Spring MVC : too much attributes in the model

I have a very basic question on spring-mvc (Model). 我对spring-mvc(模型)有一个非常基本的问题。 I was working on a project in which we were setting so many addributes in Model(ie model.addAttribute(..). My question is that Is there any design-patterns that i can use to avoid so many addAttributes? 我正在做一个项目,在这个项目中我们在Model(即model.addAttribute(..))中设置了许多addributes。我的问题是,有没有可以避免使用太多addAttributes的设计模式?

I know that I can create a bean/ form and inside it I can create respective setters/getters also but I am just looking for any other option if available. 我知道我可以创建一个bean /表单,并且在其中也可以创建各自的setter / getter,但是我只是在寻找其他任何可用的选项。

Please suggest. 请提出建议。

There is no special design pattern, just some Spring or general techniques to avoid too much addAttribute calls inside a given controller. 没有特殊的设计模式,只有一些Spring或通用技术可以避免在给定控制器内部进行过多的addAttribute调用。

If you have attributes that you will always need in your view (like a particular object, a list, booleans such as "isXXXActivated" or "showThis", etc.), you could just add methods of the sort in your controller : 如果您具有视图中始终需要的属性(例如特定对象,列表,布尔值,例如“ isXXXActivated”或“ showThis”等),则可以在控制器中添加以下排序方法:

@ModelAttribute("isXXXActivated")
public boolean isXXXActivated(){
    return isXXXActivated;
}

This will add "isXXXActivated" in your model everytime your controller is called. 每次调用控制器时,都会在模型中添加“ isXXXActivated”。

If you add the same attributes accross all your controllers, you could consider adding them in a super controller (a spring @Controller can extend another @Controller without problems). 如果在所有控制器上添加相同的属性,则可以考虑将它们添加到超级控制器中(spring @Controller可以扩展另一个@Controller而不出现问题)。

Finally, if some attributes belong to a group, you can group them as fields of an object. 最后,如果某些属性属于一个组,则可以将它们分组为对象的字段。 Then you just add this object as an attribute. 然后,您只需将此对象添加为属性。 Example : grouping display conditions into a Display class. 示例:将显示条件分组为Display类。

If you want to use a design pattern to solve a problem you really need to look at how all of them interact. 如果您想使用设计模式来解决问题,那么您确实需要查看它们之间如何相互作用。 Have you looked up different design patterns? 您是否查找了不同的设计模式? Have you considered making more Objects so you can split them up and generalize them, template method if you know design patterns. 您是否考虑过制作更多对象,以便可以将它们分解并归纳为模板方法(如果您知道设计模式)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM