What is a JavaBean exactly?

后端 未结 19 1622
清酒与你
清酒与你 2020-11-22 01:55

I understood, I think, that a \"Bean\" is a Java class with properties and getters/setters. As much as I understand, it is the equivalent of a C struct. Is that true?

<
19条回答
  •  被撕碎了的回忆
    2020-11-22 02:33

    Just a little background/update on the bean concept. Many other answers actually have the what but not so much why of them.

    They were invented early on in Java as part of building GUIs. They followed patterns that were easy for tools to pull apart letting them create a properties panel so you could edit the attributes of the Bean. In general, the Bean properties represented a control on the screen (Think x,y,width,height,text,..)

    You can also think of it as a strongly typed data structure.

    Over time these became useful for lots of tools that used the same type of access (For example, Hibernate to persist data structures to the database)

    As the tools evolved, they moved more towards annotations and away from pulling apart the setter/getter names. Now most systems don't require beans, they can take any plain old java object with annotated properties to tell them how to manipulate them.

    Now I see beans as annotated property balls--they are really only useful for the annotations they carry.

    Beans themselves are not a healthy pattern. They destroy encapsulation by their nature since they expose all their properties to external manipulation and as they are used there is a tendency (by no means a requirement) to create code to manipulate the bean externally instead of creating code inside the bean (violates "don't ask an object for it's values, ask an object to do something for you"). Using annotated pojos with minimal getters and no setters is much more OO restoring encapsulation and with the possibility of immutability.

    By the way, as all this stuff was happening someone extended the concept to something called Enterprise Java Beans. These are... different. and they are complicated enough that many people felt they didn't understand the entire Bean concept and stopped using the term. This is, I think, why you generally hear beans referred to as POJOs (since every java object is a POJO this is technically OK, but when you hear someone say POJO they are most often thinking about something that follows the bean pattern)

提交回复
热议问题