简体   繁体   English

Java Bean的一个很好的用例是什么?

[英]What is a good use case of Java Beans?

I just saw the Java Beans specification. 我刚刚看到了Java Beans规范。 I felt that using only getters, setters and empty constructor will make code more hectic plus developer needs to manage track to set all the required instances properly. 我觉得只使用getter,setter和空构造函数会使代码更加繁忙,而且开发人员需要管理track以正确设置所有必需的实例。

Could somebody point me a good use case for using such design? 有人能指出一个使用这种设计的好用例吗? I am unable to get a feel of it. 我无法理解它。 There is one use I can think of - "When you need to create an Instance of a class such that its data members will be decided later in the code." 我可以想到一个用途 - “当你需要创建一个类的实例,以便稍后在代码中决定它的数据成员。”

EDIT: Guys I am not initiating a discussion. 编辑:伙计们我不是在开始讨论。 Don't want to discuss advantages/disadvantages. 不想讨论优点/缺点。 I am not looking for current libraries like spring etc which makes it mandatory to use Beans. 我不是在寻找像spring等当前的库,这使得它必须使用Beans。 I am looking for an example to understand engineering benefits Java beans would bring. 我正在寻找一个例子来了解Java bean带来的工程优势。 "Just one example where Java Beans design would help" “只是Java Beans设计可以帮助的一个例子”

A number of libraries and specifications (eg JPA, JavaEL) use the Java Beans spec and rely on exactly that behavior. 许多库和规范(例如JPA,JavaEL)使用Java Beans规范并完全依赖于该行为。

Using getters and setters has the advantage of letting you add code inside those methods, eg to create "virtual" properties which are calculated at runtime rather than stored in a field. 使用getter和setter的优点是可以在这些方法中添加代码,例如创建在运行时计算而不是存储在字段中的“虚拟”属性。

Additionally using getters and setters allows other frameworks to wrap those methods and provide additional functionality like change logging etc. In many cases this is done by internally creating a subclass and overriding the getters and setters. 此外,使用getter和setter允许其他框架包装这些方法并提供其他功能,如更改日志记录等。在许多情况下,这是通过内部创建子类并覆盖getter和setter来完成的。 The user would not notice that since that "weaving" or "proxying" is often done at runtime. 用户不会注意到,因为“编织”或“代理”通常在运行时完成。 Hibernate for example uses this to provide lazy loading functionality when you call a getter to access a related collection or entity. 例如,当您调用getter访问相关集合或实体时,Hibernate使用它来提供延迟加载功能。

Update : 更新

As per request an example for "virtual" properties: 根据请求,“虚拟”属性的示例:

Assume you have a Person bean which has the fields firstName and lastName . 假设您有一个Person bean,其字段为firstNamelastName You could add a read-only virtual property name by providing the following getter: 您可以通过提供以下getter来添加只读虚拟属性name

public String getName() {
  return getFirstName() + " " + getLastName();
}

Update 2: 更新2:

Another note on why getters and setters are necessary: this basically comes from how Java works. 关于为何需要getter和setter的另一个注释:这主要来自Java的工作原理。 Languages that directly support properties, like C#, would allow you to write code like person.firstName = "Joe"; 直接支持属性的语言(如C#)允许您编写类似person.firstName = "Joe";代码person.firstName = "Joe"; and still use a setter if there is one or throw an error if the property is read-only. 并且如果有一个setter仍然使用setter,或者如果该属性是只读的则抛出错误。 So if you'd add a setter for firstName those languages would internally translate firstName = "Joe" to setFirstName("Joe") without the developer having to change anything - quite an elegant solution. 因此,如果你为firstName添加一个setter,那么这些语言会在内部将firstName = "Joe"setFirstName("Joe")而开发人员不必改变任何东西 - 这是一个非常优雅的解决方案。 :) :)

Since Java doesn't support that, we have to always provide accessor methods (setters/getters) even if they don't do anything special - just in case they might need to be changed in the future. 由于Java不支持,我们必须始终提供访问器方法(setter / getters),即使它们没有做任何特殊操作 - 以防万一它们将来可能需要更改。

getters & setters ensures the basic object oriented concept - Encapsulation getters&setters确保the basic object oriented concept - Encapsulation

Imagine you wrote the code for a class and another dozen programmers from your company all wrote programs that used your class. 想象一下,你为一个类编写了代码,而你公司的另外十几个程序员都编写了使用你的类的程序。 So , anyone can change your instance variable & it may harm your code . 因此,任何人都可以更改您的实例变量,它可能会损害您的代码。

So you should 所以你应该

Keep instance variables protected (with an access modifier, often private ). Keep instance variables protected (使用access modifier, often private )。

Make public accessor methods , and force calling code to use those methods rather than directly accessing the instance variable . 制作public accessor methods ,并强制调用代码使用这些方法rather than directly accessing the instance variable

Their code brought out errors in your code. 他们的代码在您的代码中带来了错误。

look the following example 看下面的例子

public class MyClass{
public int size;
public int weight;
...
}
public class OthersClass {
public static void main (String [] args) {
MyClass myClass= new MyClass();
myClass.size = -5; // Legal but bad logic
}
}

An empty constructor is needed to create a new instance via reflection by your persistence framework. 需要空构造函数来通过持久性框架的反射来创建新实例。 If you don't provide any additional constructors with arguments for the class, you don't need to provide an empty constructor because you get one per default. 如果您没有为该类提供任何其他带有参数的构造函数,则不需要提供空构造函数,因为每个默认值都会得到一个。

In my experience it is to prevent the situation where someone adds a constructor with parameters, and thus effectively removes the default constructor. 根据我的经验,它是为了防止有人添加带参数的构造函数的情况,从而有效地删除默认构造函数。 By implementing the default constructor explicitly that is more unlikely to happen. 通过显式实现默认构造函数更不可能发生。

Also, i guess you are imagining a class with lots of attibutes that will be hard to fill only with getters and setters, but also note this points: 另外,我猜你想象的是一个有很多属性的课程,这个课程很难只用吸气剂和制定者来填充,但也注意到这一点:

  • Getters will automatize the view part. Getters将自动化视图部分。
  • Setters will allow you to add validation or error control if necessary. 如有必要,Setter将允许您添加验证或错误控制。

Beyond the actual advantages and disadvantages of JavaBeans spec, I think it's important to remember that it is a specification introduced in 1996 to enable the visual editing of Java code. 除了JavaBeans规范的实际优点和缺点之外,我认为重要的是要记住它是1996年引入的一个规范,用于实现Java代码的可视化编辑。

I don't know if this approach to programming succeeded and has been adopted (I have never used it, personally). 我不知道这种编程方法是否成功并已被采用(我个人从未使用过它)。 What I know is that the specification continued to live and to be applied very widely (IMHO sometimes also in contexts in which was not the most suitable). 我所知道的是规范继续存在并且应用得非常广泛(恕我直言,有时也适用于不适合的情况)。

I think the most useful place in which JavaBeans can be used is a framework . 我认为可以使用JavaBeans最有用的地方是框架 A good example is Spring. 一个很好的例子是Spring。 A JavaBean class is very suitable whenever class instantiation is not responsible of the programmer, but is delegated to the application container (for example via reflection). 只要类实例化不负责程序员,JavaBean类就非常适合,但是被委托给应用程序容器(例如通过反射)。

JavaBeans, as you've described above, can be employed as DAO (Data Access Objects) for retrieving and saving data to a (SQL primarily) Database. 如上所述,JavaBeans可以用作DAO(数据访问对象),用于检索数据并将数据保存到(主要是SQL)数据库。 They are useful where all you really care about is the data 它们非常有用,您真正关心的只是数据

Many people will tell you that Java Beans are so much better than using plain Java objects that act as "data transfer objects". 许多人会告诉你,Java Beans比使用充当“数据传输对象”的普通Java对象要好得多。

But other people, for example this guy here in his well known book https://cleansourcecode.files.wordpress.com/2013/10/clean-code.pdf suggests that most often, "beans" and getters and setters do have not much additional value (the whole chapter 6 is devoted to this question). 但其他人,例如这个人在他着名的书籍https://cleansourcecode.files.wordpress.com/2013/10/clean-code.pdf中表明,大多数情况下,“豆子”,吸气剂和制定者都没有更多的附加价值(整个第6章专门讨论这个问题)。

So you should decide for yourself (and probably with your team mates) if your problem is better solved with "Java Beans" or "plain data transfer objects". 因此,如果使用“Java Bean”或“普通数据传输对象”更好地解决问题,您应该自己决定(可能还有您的队友)。

Sure, "beans" force you to use setters, which allow you to later add validation. 当然,“beans”强制您使用setter,这允许您稍后添加验证。 On the other hand: such a change modifies the semantics of your methods; 另一方面:这样的改变会修改方法的语义 ; and it might be plain wrong that all of a sudden a setter does validation and starts throwing exceptions. 突然之间,一个setter会进行验证并开始抛出异常,这可能是完全错误的。 Because, if you change the contract of your methods; 因为,如果你改变你的方法的合同 ; you might not want to do that implicitly under the covers. 你可能不想在隐蔽的情况下做到这一点。

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

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