Spring 4.x bean operation and Beanwrapper

Source: Internet
Author: User

The way in which Beanwrapper works is partly represented by its name: it wraps a bean on which to perform actions, such as setting and retrieving properties.

A very important class in the beans package is the implementation of the Beanwrapper interface and its response (BEANWRAPPERIMPL). Beanwrapper provides functionality (either individually or in bulk) to set and get property values, get property descriptions, and query properties to determine whether they are readable or writable. At the same time, Beanwrapper provides a child property that supports nested properties and can set the infinite depth of a property. In addition, Beanwrapper supports the addition of standard JavaBeans propertychangelisteners and Vetoablechangelistener, eliminating the need to provide code in the target class. Last but not least, Beanwrapper provides settings or indexed property support. Beanwrapper is not typically used directly for application code, but for DataBinder and Beanfactory.

The way in which Beanwrapper works is partly represented by its name: it wraps a bean on which to perform actions, such as setting and retrieving properties.

1 setting and getting the underlying and nested properties

Using the setPropertyValue (s) and GetPropertyValue (s) methods to set and get properties, there are two variants. A more detailed description is found in spring's Javadoc.

Examples of table properties

An expression Describe
Name Represents the property name name corresponding to method GetName () or Isname () and SetName ().
Account.name A nested property that represents the property account name, corresponding to the method Getaccount (). SetName () or Getaccount (). GetName ().
ACCOUNT[2] Represents the third element of an indexed property account. The type of an indexed property can be an array, list, or other natural sorted collection.
Account[companyname] Represents the value of the Map entity index, and the key is Compenyname.

Below you will find some examples of using beanwrapper to get and set properties.

Public class Company {

    private String name;
    private Employee Managingdirector;

    public String getName () {
        return this.name;
   

    public void SetName (String name) {
         this.name = name;
   }

    public Employee getmanagingdirector () {
        return this.managingdirector;
   }

    public void Setmanagingdirector (Employee managingdirector) {
         this.managingdirector = Managingdirector;
   }
}

public class Employee {
private String name;
private float salary;

Public String GetName () {
return this.name;
}

public void SetName (String name) {
THIS.name = name;
}

public float getsalary () {
return salary;
}

public void Setsalary (float salary) {
This.salary = salary;
}
}

The following code snippet shows some examples of how to retrieve and manipulate Some properties of Companies and Employees instances:

Beanwrapper company = new Beanwrapperimpl (new company ());
Set up company name
Company.setpropertyvalue ("name", "Some Company Inc.");
You can do that.
PropertyValue value = new PropertyValue ("name", "Some Company Inc.");
Company.setpropertyvalue (value);

Create a supervisor and bind to the company
Beanwrapper Jim = new Beanwrapperimpl (new Employee ());
Jim.setpropertyvalue ("name", "Jim Stravinsky");
Company.setpropertyvalue ("Managingdirector", Jim.getwrappedinstance ());

To retrieve the salary of the supervisor through the company
float salary = (float) company.getpropertyvalue ("Managingdirector.salary");

2 built-in propertyeditor implementation

Spring uses the concept of PropertyEditor to act on conversions between object and string. If you understand it, it can sometimes be convenient to represent properties in different ways rather than the object itself. For example, date can be expressed as a human-readable way (as the string ' 2007-14-09 '), however, we can still be able to trace human readable back to the original date (even better: convert any date to human readable form, back to date object). This behavior can be done by registering a custom editor of the Java.beans.PropertyEditor type. Register the custom editor on Beanwrapper or in a specific IOC container as described in the previous section, specifying how to convert a property to a specific type.

Some examples of editing attributes in spring are:

    • Use Propertyeditors to set properties on the bean. When Java.lang.String is declared as a property value for some beans in an XML file, (if the property has a class parameter set) Spring uses Classeditor to try to parse the parameter into a class object.

    • Using all types of propertyeditors to parse HTTP request parameters in the Spring MVC framework, you can manually bind all Commandcontroller subclasses.

Spring has a range of built-in propertyeditors. Each propertyeditors is listed in the Org.springframework.beans.propertyeditors package. Most, but not all (as shown below), are registered by Beanwrapperimpl by default. In some way the property editor is configurable, and you can of course register your own variants to override the default property editor:

Table built-in Property editor

Class
Description
Bytearraypropertyeditor
Edit the byte array. The string is converted to the corresponding byte representation. The default is registered by Beanwrapperimpl.
Classeditor Parsing a string represents a class that is a real class and vice versa. Throws a illegalargumentexception when a class is not found. The default is registered by Beanwrapperimpl.
Custombooleaneditor The Boolean property of the custom property editor. The default is registered by Beanwrapperimpl, but can be overridden by registering a custom instance as a custom editor.
CustomCollectionEditor The collection property editor, which transforms any source collection to the specified target collection type.
Customdateeditor
Java.util.Date custom Property Editor, supports custom DateFormat. The default is not registered. The appropriate format must be registered according to user requirements.
Customnumbereditor
Any number subclass, such as an Integer, Long, Float, double, custom property editor. The default is registered by Beanwrapperimpl, but can be overridden by registering a custom instance as a custom editor.
Fileeditor
The string can be parsed as a Java.io.File object. The default is registered by Beanwrapperimpl.
Inputstreameditor A one-way property editor that converts a string to InputStream (through intermediate resourceeditor and Resource), so inputstream can be set directly to a string. Note that the default does not turn off inputstream! for you The default is registered by Beanwrapperimpl.
Localeeditor
The ability to parse a string as a locale object and vice versa (the string format provides the same functionality as the ToString () method of [country] [variant],locale). The default is registered by Beanwrapperimpl.
Patterneditor The ability to parse a string into a Java.util.regex.Pattern object and vice versa.
Propertieseditor The ability to convert a string to a Properties object (using the format defined in the Javadocs of the Java.util.Properties Class). The default is registered by Beanwrapperimpl.
Stringtrimmereditor
A property editor that removes whitespace from both sides of the string. Allows you to choose to convert an empty string to null. The default is not registered and must be registered by the user.
UrlEditor The ability to parse a string representing a URL as a real URL object. The default is registered by Beanwrapperimpl.

Spring uses Java.beans.PropertyEditorManager to set the path of the property editor required for the search. The search path also includes sun.bean.editors, including propertyeditor implementation types, such as font, color, and most primitive types. Also note that the standard JavaBeans infrastructure will automatically discover the PropertyEditor class (you do not have to show registration for them) if they are in the same package as the class being processed and the same name as the class being processed, using the editor end; For example, there is a possible class and package structure, Fooeditor will be considered a propertyeditor with the Foo type attribute.

Com
Chank
Pop
Foo
Fooeditor//Foo class PropertyEditor

Note that you can also use the standard BeanInfo JavaBeans mechanism here. Find the following example using the BeanInfo mechanism to explicitly register the classes associated with the properties of one or more propertyeditor instances.

Com
Chank
Pop
Foo
Foobeaninfo//Foo class BeanInfo

The following is the Java source code that references the Foobeaninfo class. This associates the age attribute of the customnumbereditor with the Foo class.

public class Foobeaninfo extends Simplebeaninfo {

Public propertydescriptor[] Getpropertydescriptors () {
try {
Final PropertyEditor Numberpe = new Customnumbereditor (Integer.class, true);
PropertyDescriptor agedescriptor = new PropertyDescriptor ("Age", Foo.class) {
Public propertyeditor createpropertyeditor (Object Bean) {
return Numberpe;
};
};
return new propertydescriptor[] {agedescriptor};
}
catch (Introspectionexception ex) {
throw new Error (ex.tostring ());
}
}
}

Register for additional custom propertyeditors

When you set the Bean property as a string value, the Spring IOC container ends up using standard JavaBeans propertyeditor to convert these strings to complex property types. Spring has pre-registered a series of custom PropertyEditor (for example, to convert a class name string to a real class object). In addition, Java's standard JavaBeans propertyeditor lookup mechanism allows propertyeditor classes to be just as appropriate to name and place classes that are placed in the same package to provide support for automatic lookups.

If you need to register additional custom propertyeditor, there are several mechanisms. Most manual methods, usually inconvenient or not recommended, simply use the Registercustomeditor () method of the Configurablebeanfactory interface, assuming you have beanfactory references. Another, more convenient mechanism is to use a specific bean factory called Customeditorconfigurer after the processor. Although the Bean Factory post processor can be used with the beanfactory implementation, Customeditorconfigurer has a nested property setting, so it is highly recommended to use ApplicationContext, It can be deployed in a place similar to any other bean, and is automatically detected and applied.

Note that all bean factory and application contexts automatically use a series of built-in property editors to handle property conversions by using something called Beanwrapper. The standard attribute editor for Beanwrapper registration is listed in the previous section of the article. In addition, ApplicationContext also overrides or adds an additional editor to handle resource lookups that are appropriate for a particular application context type.

The standard JavaBeans PropertyEditor instance is used to convert property values represented as strings to real complex type properties. Customeditorconfigurer, a bean factory post processor, can be used to easily add additional PropertyEditor instance support for ApplicationContext.

Consider a user class Exotictype, and another class Dependsonexotictype needs to be exotictype set to a property:

package example;

public class Exotictype {

private String name;

Public Exotictype (String name) {
THIS.name = name;
}
}

public class Dependsonexotictype {

Private Exotictype type;

public void SetType (Exotictype type) {
This.type = type;
}
}

When the property is set, we want to be able to assign the property type to a string, and PropertyEditor will convert the string to an actual Exotictype instance behind the scenes:

<bean id= "Sample" class= "example. Dependsonexotictype ">
<property name= "type" value= "Anameforexotictype"/>
</bean>

PropertyEditor the implementation might look like this:

Convert String to Exotictype object
package example;

public class Exotictypeeditor extends PropertyEditorSupport {

public void Setastext (String text) {
SetValue (New Exotictype (Text.touppercase ()));
}
}

Finally, we use Customeditorconfigurer to register the new propertyeditor for ApplicationContext, which will be able to use it when needed:

<bean class= "Org.springframework.beans.factory.config.CustomEditorConfigurer" >
<property name= "Customeditors" >
<map>
<entry key= "Example. Exotictype "Value=" example. Exotictypeeditor "/>
</map>
</property>
</bean>

Using Propertyeditorregistrars

Another mechanism for registering a property editor with the spring container is to create and use a propertyeditorregistrars. This interface is particularly useful when you need to use the same property editor set in different situations: write a corresponding registrar and reuse in each case.

The propertyeditorregistrars is used with an interface called Propertyeditorregistry, an interface that implements Spring Beanwrapper (and DataBinder). Propertyeditorregistrars is especially handy when federated Customeditorconfigurer is used, calling Setpropertyeditorregistrars (..) Exposure properties: Propertyeditorregistrars Adding a customeditorconfigurer in this way can be easily shared between DataBinder and spring MVC controllers. In addition, it avoids the need to synchronize the custom editor: Propertyeditorregistrar is expected to create a new PropertyEditor instance for each bean.

Using Propertyeditorregistrar may be best illustrated with an example. First, you need to create your own Propertyeditorregistrar implementation:

Package com.foo.editors.spring;

Public final class Custompropertyeditorregistrar implements Propertyeditorregistrar {

public void Registercustomeditors (Propertyeditorregistry registry) {

Expect to create a new PropertyEditor instance
Registry.registercustomeditor (Exotictype.class, New Exotictypeeditor ());

You may be here to define many custom property editors that you need
}
}

See Org.springframework.beans.support.REsourceEditorRegistrar for examples of implementing Propertyeditorregistrar. Note that in the implementation of the Registercustomeditors (..) method to create a new instance of each property editor.

Next, we configure a customeditorconfigurer and inject an instance of our Custompropertyeditorregistrar:

<bean class= "Org.springframework.beans.factory.config.CustomEditorConfigurer" >
<property name= "Propertyeditorregistrars" >
<list>
<ref bean= "Custompropertyeditorregistrar"/>
</list>
</property>
</bean>

<bean id= "Custompropertyeditorregistrar"
class= "Com.foo.editors.spring.CustomPropertyEditorRegistrar"/>

Finally, a bit off the focus of this article, if you use the Spring MVC Web framework, it is convenient to use Propertyeditorregistrar and data-binding controllers (such as Simpleformcontroller) together.

Public final class Registerusercontroller extends Simpleformcontroller {

Private final Propertyeditorregistrar Custompropertyeditorregistrar;

Public Registerusercontroller (Propertyeditorregistrar Propertyeditorregistrar) {
This.custompropertyeditorregistrar = Propertyeditorregistrar;
}

protected void Initbinder (HttpServletRequest request,
Servletrequestdatabinder Binder) throws Exception {
This.customPropertyEditorRegistrar.registerCustomEditors (binder);
}

Other ways to register your users
}

This style of PropertyEditor registration can lead to concise code (Implementation Initbinder (..) is a long line), and allows common PropertyEditor registration code to be encapsulated in a class, and then as many controllers as possible need to be shared.

Spring 4.x bean operation and Beanwrapper

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.