- The Java EE 5 Tutorial
- JavaBeans Component Design Conventions
- Creating and Using a JavaBeans Component
- Setting JavaBeans Component Properties
- @Bean
- Объявление бина
- Зависимости бинов
- Java Bean Example
- 2. JavaBean Features
- Features:
- 3. Structure of Java Bean class
- 4. JavaBean Example
- 5. Advantages and Disadvantages of JavaBean
- Pros:
- Cons:
The Java EE 5 Tutorial
JavaBeans components are Java classes that can be easily reused and composed together into applications. Any Java class that follows certain design conventions is a JavaBeans component.
JavaServer Pages technology directly supports using JavaBeans components with standard JSP language elements. You can easily create and initialize beans and get and set the values of their properties.
JavaBeans Component Design Conventions
JavaBeans component design conventions govern the properties of the class and govern the public methods that give access to the properties.
A JavaBeans component property can be:
- Read/write, read-only, or write-only
- Simple, which means it contains a single value, or indexed, which means it represents an array of values
A property does not have to be implemented by an instance variable. It must simply be accessible using public methods that conform to the following conventions:
- For each readable property, the bean must have a method of the form:
PropertyClass getProperty()
setProperty(PropertyClass pc)
In addition to the property methods, a JavaBeans component must define a constructor that takes no parameters.
The Duke’s Bookstore application JSP pages bookstore.jsp, bookdetails.jsp, catalog.jsp, and showcart.jsp, all located at tut-install/javaeetutorial5/examples/web/bookstore2/web, use the tut-install/javaeetutorial5/examples/web/bookstore2/src/java/com/sun/bookstore2/database/BookDB.java JavaBeans component.
BookDB provides a JavaBeans component front end to the access object BookDBAO. The JSP pages showcart.jsp and cashier.jsp access the bean tut-install/javaeetutorial5/examples/web/bookstore/src/com/sun/bookstore/cart/ShoppingCart.java, which represents a user’s shopping cart.
The BookDB bean has two writable properties, bookId and database, and three readable properties: bookDetails, numberOfBooks, and books. These latter properties do not correspond to any instance variables but rather are a function of the bookId and database properties.
package database; public class BookDB < private String bookId = "0"; private BookDBAO database = null; public BookDB () < >public void setBookId(String bookId) < this.bookId = bookId; >public void setDatabase(BookDBAO database) < this.database = database; >public Book getBook() throws BookNotFoundException < return (Book)database.getBook(bookId); >public List getBooks() throws BooksNotFoundException < return database.getBooks(); >public void buyBooks(ShoppingCart cart) throws OrderException < database.buyBooks(cart); >public int getNumberOfBooks() throws BooksNotFoundException < return database.getNumberOfBooks(); >>
Creating and Using a JavaBeans Component
To declare that your JSP page will use a JavaBeans component, you use a jsp:useBean element. There are two forms:
The second form is used when you want to include jsp:setProperty statements, described in the next section, for initializing bean properties.
The jsp:useBean element declares that the page will use a bean that is stored within and is accessible from the specified scope, which can be application, session, request, or page. If no such bean exists, the statement creates the bean and stores it as an attribute of the scope object (see Using Scope Objects). The value of the id attribute determines the name of the bean in the scope and the identifier used to reference the bean in EL expressions, other JSP elements, and scripting expressions (see Chapter 9, Scripting in JSP Pages). The value supplied for the class attribute must be a fully qualified class name. Note that beans cannot be in the unnamed package. Thus the format of the value must be package-name.class-name.
The following element creates an instance of mypkg.myLocales if none exists, stores it as an attribute of the application scope, and makes the bean available throughout the application by the identifier locales:
Setting JavaBeans Component Properties
The standard way to set JavaBeans component properties in a JSP page is by using the jsp:setProperty element. The syntax of the jsp:setProperty element depends on the source of the property value. Table 5-6 summarizes the various ways to set a property of a JavaBeans component using the jsp:setProperty element.
Syntax rules of attribute values used in this table:
- beanName must be the same as that specified for the id attribute in a useBean element.
- There must be a setPropName method in the JavaBeans component.
- paramName must be a request parameter name.
Table 5-6 Valid Bean Property Assignments from String Values
@Bean
@Bean – это аннотация уровня метода и прямой аналог элемента на XML. Аннотация поддерживает некоторые атрибуты, предлагаемые , такие как:
Вы можете использовать аннотацию @Bean в классе с аннотацией @Configuration или в классе с аннотацией @Component .
Объявление бина
Чтобы объявить бин, можно аннотировать метод с помощью @Bean . Этот метод используется для регистрации определения бина в ApplicationContext того типа, который задан в качестве возвращаемого значения метода. По умолчанию имя бина совпадает с именем метода. В следующем примере показано объявление метода с аннотацией @Bean :
@Configuration public class AppConfig < @Bean public TransferServiceImpl transferService() < return new TransferServiceImpl(); >>
@Configuration class AppConfig
Предшествующая конфигурация в точности эквивалентна следующей на основе XML в Spring:
Оба объявления делают бин с именем transferService доступным в ApplicationContext , привязанном к экземпляру объекта типа TransferServiceImpl , как показано на следующем текстовом изображении:
transferService -> com.acme.TransferServiceImpl
Также можно использовать методы по умолчанию для определения бинов. Это позволяет создавать конфигурации бинов путем реализации интерфейсов с определениями бинов в методах по умолчанию.
public interface BaseConfig < @Bean default TransferServiceImpl transferService() < return new TransferServiceImpl(); >> @Configuration public class AppConfig implements BaseConfig
Можно также объявить свой метод, аннотированный @Bean , с помощью возвращаемого типа интерфейса (или базового класса), как показано в следующем примере:
@Configuration public class AppConfig < @Bean public TransferService transferService() < return new TransferServiceImpl(); >>
@Configuration class AppConfig < @Bean fun transferService(): TransferService < return TransferServiceImpl() >>
Однако это ограничивает видимость для прогнозирования расширенного типа указанным типом интерфейса (TransferService ). Затем, когда полный тип (TransferServiceImpl ) единожды распознается контейнером, создается экземпляр затронутого бина-одиночки. Экземпляры бинов-одиночек без отложенной инициализации создаются в соответствии с порядком их объявления, поэтому вы можете заметить разные результаты согласования по типам в зависимости от того, когда другой компонент пытается выполнить согласование по необъявленному типу (например, @Autowired TransferServiceImpl , который разрешается только после создания экземпляра бина transferService ).
Если вы постоянно ссылаетесь на свои типы по объявленному интерфейсу службы, то ваши возвращаемые типы, помеченные аннотацией @Bean , могут без проблем следовать этому проектному решению. Однако для компонентов, реализующих несколько интерфейсов, или для компонентов, на которые потенциально можно ссылаться по их типу реализации, безопаснее объявить максимально конкретный возвращаемый тип (по крайней мере, настолько конкретный, насколько этого требуют точки внедрения, ссылающиеся на ваш бин).
Зависимости бинов
Метод, аннотированный @Bean , может иметь произвольное количество параметров, которые описывают зависимости, необходимые для создания этого бина. Например, если нашему TransferService требуется AccountRepository , мы можем осуществить эту зависимость с помощью параметра метода, как показано в следующем примере:
@Configuration public class AppConfig < @Bean public TransferService transferService(AccountRepository accountRepository) < return new TransferServiceImpl(accountRepository); >>
Java Bean Example
In computing based on the Java Platform, JavaBeans are classes that encapsulate many objects into a single object (the bean). They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. The name “Bean” was given to encompass this standard, which aims to create reusable software components for Java.
2. JavaBean Features
According to Java white paper, it is a reusable software component. A bean encapsulates many objects into one object so that we can access this object from multiple places. Moreover, it provides easy maintenance.
Features:
1. Introspection – Introspection is a process of analyzing a Bean to determine its capabilities. This is an essential feature of the Java Beans API because it allows another application such as a design tool, to obtain information about a component.
2. Properties – A property is a subset of a Bean’s state. The values assigned to the properties determine the behaviour and appearance of that component. They are set through a setter method and can be obtained by a getter method.
3. Customization – A customizer can provide a step-by-step guide that the process must follow to use the component in a specific context.
4. Events – Beans may interact with the EventObject EventListener model.
5. Persistence – Persistence is the ability to save the current state of a Bean, including the values of a Bean’s properties and instance variables, to nonvolatile storage and to retrieve them at a later time.
6. Methods – A bean should use accessor methods to encapsulate the properties. A bean can provide other methods for business logic not related to the access to the properties.
3. Structure of Java Bean class
- It should be public in nature.
- The return-type should be void.
- The setter method should be prefixed with set.
- It should take some argument i.e. it should not be no-arg method.
- It should be public in nature.
- The return-type should not be void i.e. according to our requirement we have to give return-type.
- The getter method should be prefixed with get.
- It should not take any argument.
public class TestBean < private String name; //setter method public void setName(String name) < this.name = name; >//getter method public String getName() < return name; >>
For Boolean properties getter method name can be prefixed with either “get” or “is”. But recommended to use “is”.
public class Test < private boolean empty; public boolean getName() < return empty; >public boolean isempty() < return empty; >>
4. JavaBean Example
Before going to write a JavaBean, here are some basic rules. A JavaBean should be public, should has no argument default constructor and should implement serializable interface. Keep these basic rules in mind before writing a JavaBean
The example program shown below demonstrates how to implement JavaBeans.
// Java Program of JavaBean class package com.javacodegeeks.javabean; public class Student implements java.io.Serializable < private int id; private String name; public Student() < >public void setId(int id) < this.id = id; >public int getId() < return id; >public void setName(String name) < this.name = name; >public String getName() < return name; >>
The following program is written in order to access the JavaBean class that we created above:
// Java program to access JavaBean class package com.javacodegeeks.javabean; public class Test < public static void main(String args[]) < Student s = new Student(); // object is created s.setName("JavaCodeGeeks"); // setting value to the object System.out.println(s.getName()); >>
5. Advantages and Disadvantages of JavaBean
Pros:
- The properties, events, and methods of a bean can be exposed to another application.
- 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 bean.
- The configuration settings of a bean can be saved to persistent storage and restored.
Cons:
- A class with a zero-argument 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 cannot detect such a problem, and even if it is documented, there is no guarantee that the developer will see the documentation.
- JavaBeans are inherently mutable and so lack the advantages offered by immutable objects.
- Having to create getters for every property and setters for many, most, or all of them can lead to an immense quantity of boilerplate code.