使用 JavaBean 的地方?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1727603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Places where JavaBeans are used?
提问by Sidharth
What is a JavaBean and why do I need it? Since I can create all apps with the class and interface structure? Why do I need beans? And can you give me some examples where beans are essential instead of classes and interfaces?
什么是 JavaBean,我为什么需要它?既然我可以用类和接口结构创建所有应用程序?为什么我需要豆子?你能给我一些例子,其中 bean 是必不可少的,而不是类和接口吗?
Please explain the essentiality of a bean in the below context:
请在以下上下文中解释 bean 的重要性:
- Wep apps
- Standalone apps
- 网页应用
- 独立应用
采纳答案by BalusC
They often just represents real world data. Here's a simple example of a Javabean:
它们通常只代表真实世界的数据。下面是一个 Javabean 的简单示例:
public class User implements java.io.Serializable {
// Properties.
private Long id;
private String name;
private Date birthdate;
// Getters.
public Long getId() { return id; }
public String getName() { return name; }
public Date getBirthdate() { return birthdate; }
// Setters.
public void setId(Long id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setBirthdate(Date birthdate) { this.birthdate = birthdate; }
// Important java.lang.Object overrides.
public boolean equals(Object other) {
return (other instanceof User) && (id != null) ? id.equals(((User) other).id) : (other == this);
}
public int hashCode() {
return (id != null) ? (getClass().hashCode() + id.hashCode()) : super.hashCode();
}
public String toString() {
return String.format("User[id=%d,name=%s,birthdate=%d]", id, name, birthdate);
}
}
Implementing Serializable
is not per se mandatory, but very useful if you'd like to be able to persist or transfer Javabeans outside Java's memory, e.g. in harddisk or over network.
实现Serializable
本身并不是强制性的,但如果您希望能够在 Java 内存之外(例如在硬盘中或通过网络)持久化或传输 Javabean,则非常有用。
In for example a DAO class you can use it to create a list of users wherein you storethe data of the user
table in the database:
例如,在 DAO 类中,您可以使用它来创建用户列表,您可以在其中将表的数据存储user
在数据库中:
List<User> users = new ArrayList<User>();
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getLong("id"));
user.setName(resultSet.getString("name"));
user.setBirthdate(resultSet.getDate("birthdate"));
users.add(user);
}
return users;
In for example a Servlet class you can use it to transferdata from the database to the UI:
例如,在 Servlet 类中,您可以使用它来将数据从数据库传输到 UI:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
List<User> users = userDAO.list();
request.setAttribute("users", users);
request.getRequestDispatcher("users.jsp").forward(request, response);
}
In for example a JSP page you can accessit by EL, which follows the Javabean conventions, to display the data:
例如,在 JSP 页面中,您可以通过EL访问它,它遵循 Javabean 约定,以显示数据:
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Birthdate</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td><c:out value="${user.name}" /></td>
<td><fmt:formatDate value="${user.birthdate}" pattern="yyyy-MM-dd" /></td>
</tr>
</c:forEach>
</table>
Does it make sense? You see, it's kind of a conventionwhich you can use everywhere to store, transferand accessdata.
是否有意义?你看,这是一种约定,你可以在任何地方使用它来存储、传输和访问数据。
See also:
也可以看看:
回答by Esko
Beans themselves
豆子本身
JavaBeansare everywhere, they're a convention and just about every single slightly larger library out there uses those conventions to automate things. Just a few reasons why JavaBeans should be used:
JavaBeans无处不在,它们是一种约定,几乎每个稍微大一点的库都使用这些约定来自动化操作。应该使用 JavaBeans 的几个原因:
- They serialize nicely.
- Can be instantiated using reflection.
- Can otherwise be controlled using reflection very easily.
- Good for encapsulating actual data from business code.
- Common conventions mean anyone can use your beans AND YOU CAN USE EVERYONE ELSE'S BEANS without any kind of documentation/manual easily and in consistent manner.
- Very close to POJOs which actually means even more interoperability between distinct parts of the system.
- 他们很好地序列化。
- 可以使用反射来实例化。
- 否则可以很容易地使用反射进行控制。
- 适合从业务代码中封装实际数据。
- 通用约定意味着任何人都可以使用您的 bean,并且您可以轻松且一致地使用任何其他人的 bean,而无需任何类型的文档/手册。
- 非常接近POJO,这实际上意味着系统不同部分之间的互操作性更高。
Also there's of course Enterprise JavaBeanswhich are a whole another matter and shouldn't be mixed with plain JavaBeans. I just wanted to mention EJB:s because the names are similar and it's easy to get those two confused.
当然还有Enterprise JavaBeans,这是另一回事,不应与普通 JavaBeans 混合。我只想提到 EJB:s 因为名称相似,很容易将这两者混淆。
Beans in web applications
Web 应用程序中的 Bean
If you consider "normal" JavaBeans in web app context, they make more sense than wearing shoes in your legs. Since the Servlet specification requires for sessions to be serializable, it means you should store your data in session as something that's serializable - why not make it a bean then! Just throw your SomeBusinessDataBean into the session and you're good to go, laughably easy, specification-compliant and convenient.
如果您在 Web 应用程序上下文中考虑“普通”JavaBeans,那么它们比在您的腿上穿鞋更有意义。由于 Servlet 规范要求会话是可序列化的,这意味着您应该将会话中的数据作为可序列化的内容存储 - 那么为什么不将其设为 bean!只需将您的 SomeBusinessDataBean 放入会话中,您就可以开始使用了,非常简单,符合规范且方便。
Also transferring that data around the application is easy too since JavaBeans help you to decouple parts of your application completely. Think JavaBeans as a letter and various subsystems of the application as departments within a very large corporation: Dept.A mails a bunch of data to Dept.B, Dept.B doesn't know -or even care- where the data came from just as it should be and can just open the letter, read stuff from it and do its thing based on that data.
此外,围绕应用程序传输该数据也很容易,因为 JavaBeans 可以帮助您完全解耦应用程序的各个部分。将 JavaBeans 视为一个信件,将应用程序的各种子系统视为一个非常大的公司中的部门:A 部门将一堆数据邮寄给 B 部门,B 部门不知道 -甚至不关心- 数据来自哪里正如它应该的那样,并且可以打开信件,从中读取内容并根据该数据执行其操作。
Beans in standalone applications
独立应用程序中的 Bean
Actually what's above applies to standalone apps too, the only difference is that you can mess up with the UI a bit more since standalone applications have stateful UI:s while web applications have statelss UI:s which in some cases only simulate stateful UI:s. Because of this difference, it's easier to make a mess with standalone application but that's worth a whole another topic and isn't directly related to JavaBeans at all.
实际上,以上内容也适用于独立应用程序,唯一的区别是您可以稍微弄乱 UI,因为独立应用程序具有有状态的 UI:s 而 Web 应用程序具有 statelss UI:s,它在某些情况下仅模拟有状态的 UI:s . 由于这种差异,更容易弄乱独立应用程序,但这完全是另一个主题,并且根本与 JavaBeans 没有直接关系。
回答by JRL
A bean is nothing much, really. For a class to be a "bean", all it requires is:
一个豆子没什么大不了的,真的。一个类要成为一个“bean”,它只需要:
- to have a public, no argument constructor
- to be serializable (to implement the Serializable interface, either directly or through one of its super classes).
- 有一个公共的,没有参数的构造函数
- 可序列化(直接或通过其超类之一实现 Serializable 接口)。
To that, you can add getters and setters for properties of the class that conform to a specific naming convention if you want the fields to be discoverable in certain circumstances (e.g. making that class some object you can drag and drop from a visual editor in your IDE, for example).
为此,如果您希望在某些情况下可以发现字段(例如,使该类成为可以从可视化编辑器中拖放的对象),您可以为符合特定命名约定的类的属性添加 getter 和 setter。 IDE,例如)。
You can find more directly from Sun here.
回答by Vibha Sanskrityayan
A Java Bean is a software component that has been designed to be reusable in a variety of different environments. There is no restriction on the capability of a Bean. It may perform a simple function, such as checking the spelling of a document, or a complex function, such as forecasting the performance of a stock portfolio. A Bean may be visible to an end user. One example of this is a button on a graphical user interface. A Bean may also be invisible to a user. Software to decode a stream of multimedia information in real time is an example of this type of building block. Finally, a Bean may be designed to work autonomously on a user's workstation or to work in cooperation with a set of other distributed components. Software to generate a pie chart from a set of data points is an example of a Bean that can execute locally. However, a Bean that provides real-time price information from a stock or commodities exchange would need to work in cooperation with other distributed software to obtain its data.
Java Bean 是一种软件组件,它被设计为可在各种不同的环境中重用。对 Bean 的能力没有限制。它可以执行简单的功能,例如检查文档的拼写,或执行复杂的功能,例如预测股票投资组合的表现。Bean 可能对最终用户可见。一个例子是图形用户界面上的按钮。Bean 也可能对用户不可见。实时解码多媒体信息流的软件就是这种类型的构建块的一个例子。最后,Bean 可以设计为在用户工作站上自主工作或与一组其他分布式组件协同工作。从一组数据点生成饼图的软件是可以在本地执行的 Bean 的一个例子。然而,
We will see shortly what specific changes a software developer must make to a class so that it is usable as a Java Bean. However, one of the goals of the Java designers was to make it easy to use this technology. Therefore, the code changes are minimal.
我们将很快看到软件开发人员必须对类进行哪些特定更改,才能将其用作 Java Bean。然而,Java 设计者的目标之一是使这项技术的使用变得容易。因此,代码更改很少。
Advantages of Java Beans
Java Bean 的优点
A software component architecture provides standard mechanisms to deal with software building blocks. The following list enumerates some of the specific benefits that Java technology provides for a component developer:
软件组件架构提供了处理软件构建块的标准机制。以下列表列举了 Java 技术为组件开发人员提供的一些特定好处:
- A Bean obtains all the benefits of Java's "write-once, run-anywhere" paradigm.
- The properties, events, and methods of a Bean that are exposed to an application builder tool can be controlled.
- A Bean may be designed to operate correctly in different locales, which makes it useful in global markets.
- Auxiliary software can be provided to help a person configure a Bean. This software is only needed when the design-time parameters for that component are being set. It does not need to be included in the run-time environment.
- The configuration settings of a Bean can be saved in persistent storage and restored at a later time.
- A Bean may register to receive events from other objects and can generate events that are sent to other objects.
- Bean 获得了 Java 的“一次编写,随处运行”范例的所有好处。
- 可以控制暴露给应用程序构建器工具的 Bean 的属性、事件和方法。
- 一个 Bean 可能被设计为在不同的地区正确运行,这使得它在全球市场中很有用。
- 可以提供辅助软件来帮助人们配置 Bean。只有在设置该组件的设计时参数时才需要该软件。它不需要包含在运行时环境中。
- Bean 的配置设置可以保存在持久存储中并在以后恢复。
- Bean 可以注册以接收来自其他对象的事件,并且可以生成发送到其他对象的事件。
Here's a simple example of a Javabean:
下面是一个 Javabean 的简单示例:
public class MyBean implements java.io.Serializable
{
protected int theValue;
public MyBean()
{
}
public void setMyValue(int newValue)
{
theValue = newValue;
}
public int getMyValue()
{
return theValue;
}
}
This is a real Bean named MyBean that has state (the variable theValue) that will automatically be saved and restored by the JavaBeans persistence mechanism, and it has a property named MyValue that is usable by a visual programming environment. This Bean doesn't have any visual representation, but that isn't a requirement for a JavaBean component.
这是一个名为 MyBean 的真实 Bean,它具有状态(变量 theValue),该状态将被 JavaBeans 持久性机制自动保存和恢复,并且它具有一个名为 MyValue 的属性,可供可视化编程环境使用。这个 Bean 没有任何可视化表示,但这不是 JavaBean 组件的要求。