2013年9月19日 星期四

javabean, java-bean

http://zh.wikipedia.org/wiki/JavaBeans

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;
      }
}

Implementing Serializable is not mandatory but is very useful if you'd like to persist or transfer Javabeans outside Java's memory, e.g. in harddisk or over network.

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.


Benefit


  1. The properties, events, and methods of a bean that are exposed to another application can be controlled.
  2. A Bean obtains all the benefits of Java's "write-once, run-anywhere" paradigm.
  3. The properties, events, and methods of a Bean that are exposed to an application builder tool can be controlled.
  4. A Bean may be designed to operate correctly in different locales, which makes it useful in global markets.
  5. 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.
  6. The configuration settings of a Bean can be saved in persistent storage and restored at a later time.
  7. A Bean may register to receive events from other objects and can generate events that are sent to other objects.
  8. A bean may register to receive events from other objects and can generate events that are sent to those other objects.
  9. Auxiliary software can be provided to help configure a java bean.
  10. The configuration setting of bean can be saved in a persistent (持久性) storage and restored at a later time.
  11. A DAO class you can use it to create a list of users wherein you store the data of the user table in the database:
    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;
  12. transfer data from the database to the UI:
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        List<User> users = userDAO.list();
        request.setAttribute("users", users);
        request.getRequestDispatcher("users.jsp").forward(request, response);
    }
  13. access it by EL, which follows the Javabean conventions, to display the data:
    <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>

Beans themselves

JavaBeans are 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:

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.
Also there's of course Enterprise JavaBeans 
which 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.

<<Beans in web applications>>

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.

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.

<<Beans in standalone applications>>

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.

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.

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.

Advantages of Java Beans

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:

The properties, events, and methods of a bean that are exposed to another application can be controlled.
A bean may register to receive events from other objects and can generate events that are sent to those other objects.
Auxiliary software can be provided to help configure a java bean.
The configuration setting of bean can be saved in a persistent (持久性) storage and restored at a later time.
Disadvantages[edit]

JavaBeans是“一次编写,到处运行”理念的Java组件。
一个bean暴露到另一个应用程序的属性,事件和方法是可控的。
一个bean可以接收来自其他对象的事件,也可以产生事件并发送到其他对象中。
有帮助设置Bean的软件。
Bean类可以被保存在持久性存储器中,以供日后重用。


A class with a nullary constructor is subject to being instantiated in an invalid state. If such a class is instantiated manually by a developer (rather than automatically by some kind of framework), the developer might not realize that the class has been improperly instantiated. The compiler can’t detect such a problem, and even if it’s documented, there’s no guarantee that the developer will see the documentation.
Having to create a getter for every property and a setter for many, most, or all of them can lead to an immense quantity of boilerplate code.


沒有留言:

張貼留言