Wednesday, July 27, 2016

A Simple Example to Use Spring BeanWrapper and PropertyAccessorFactory

The Spring classes BeanWrapper and PropertyAccessorFactory can be used to make it easier to set the nested property values of an object. You can also use the BeanWrapper to get the values of the properties.

First suppose there are the following two object classes. One class has a property that is the other class.

public class Animal {
 private String name;
 private Body body;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Body getBody() {
  return body;
 }
 public void setBody(Body body) {
  this.body = body;
 }
 @Override
 public String toString() {
  return "Animal [name=" + name + ", body=" + body + "]";
 }
}

public class Body {
 private double weight;
 private double height;
 public double getWeight() {
  return weight;
 }
 public void setWeight(double weight) {
  this.weight = weight;
 }
 public double getHeight() {
  return height;
 }
 public void setHeight(double height) {
  this.height = height;
 }
 @Override
 public String toString() {
  return "Body [weight=" + weight + ", height=" + height + "]";
 }
}

Below is the test class.

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.PropertyValue;

public class PropertyAccessTest {
 public static void main(String[] args) {
  Animal animal = new Animal();
  animal.setBody(new Body());
  System.out.println("animal=" + animal);

  // use the wrapper to set the property values
  BeanWrapper wrapper = PropertyAccessorFactory
    .forBeanPropertyAccess(animal);
  PropertyValue p1 = new PropertyValue("body.weight", 123);
  wrapper.setPropertyValue(p1);
  PropertyValue p2 = new PropertyValue("name", "tiger");
  wrapper.setPropertyValue(p2);
  System.out.println("animal=" + animal);

  // use the wrapper to get the property values
  String[] properties = { "name", "body.weight" };
  for (String p : properties) {
  Object v = wrapper.getPropertyValue(p);
  System.out.println(p + ": " + v.getClass() + " " + v);
  }
 }
}
Running the test class generates the following result:
animal=Animal [name=null, body=Body [weight=0.0, height=0.0]]
animal=Animal [name=tiger, body=Body [weight=123.0, height=0.0]]
name: class java.lang.String tiger
body.weight: class java.lang.Double 123.0

No comments:

Post a Comment