Spring的@Required注释的推荐用法 [英] Recommended usage of Spring's @Required annotation

查看:173
本文介绍了Spring的@Required注释的推荐用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到Spring有一个 @Required 注释来标记必须设置的bean中的成员变量。

I see that Spring has a @Required annotation to mark member variables in beans that must be set.

使用此功能是否有最佳做法?

Is there a best practice for using this?

例如,可能最好在构造函数中设置这些值并明确要求这些参数(特别是在Spring之外使用时)?

For instance, might it be better to set these values in the constructor and make these parameters explicitly required (esp. when used outside of Spring)?

谢谢!

推荐答案

虽然没有直接引用 @Required 注释,但Martin Fowler提供了这个建议 ...

While not referring to the @Required annotation directly, Martin Fowler provides this advice...

他更喜欢设置构造函数而不是setter中的对象值,因为它将给你一个明确的声明,说明在一个明显的地方创建一个有效的对象意味着什么,同时它也允许你清楚通过简单地不提供setter来隐藏任何不可变的字段

He prefers to set object values in the constructor rather than in setters as it will "give you a clear statement of what it means to create a valid object in an obvious place" while it also "allows you to clearly hide any fields that are immutable by simply not providing a setter".

这篇关于Spring的@Required注释的推荐用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆