技术开发 频道

Spring工作原理探秘

  BeanWrapper的深入研究

  我们看看这个BeanWrapper是如何发挥运作的,假设我们有两个bean:

1.    public class Company {  
2.     private String name;  
3.     private Employee managingDirector;  
4.      
5.     public String getName() {    
6.    return this.name;    
7.     }  
8.     public void setName(String name) {    
9.    this.name = name;    
10.     }    
11.     public Employee getManagingDirector() {    
12.    return this.managingDirector;    
13.     }  
14.     public void setManagingDirector(Employee managingDirector) {  
15.    this.managingDirector = managingDirector;    
16.     }  
17.    }  
18.      
19.    public class Employee {  
20.     private float salary;  
21.      
22.     public float getSalary() {  
23.    return salary;  
24.     }    
25.     public void setSalary(float salary) {  
26.    this.salary = salary;  
27.     }  
28.    }  

  然后我们使用BeanWrapper来调用这两个bean:

1.    Company c = new Company();  
2.    BeanWrapper bwComp = BeanWrapperImpl(c);  
3.    // setting the company name...  
4.    bwComp.setPropertyValue("name", "Some Company Inc.");  
5.    // ... can also be done like this:  
6.    PropertyValue v = new PropertyValue("name", "Some Company Inc.");  
7.    bwComp.setPropertyValue(v);  
8.      
9.    // ok, lets create the director and tie it to the company:  
10.    Employee jim = new Employee();  
11.    BeanWrapper bwJim = BeanWrapperImpl(jim);  
12.    bwJim.setPropertyValue("name", "Jim Stravinsky");    
13.    bwComp.setPropertyValue("managingDirector", jim);  
14.      
15.    // retrieving the salary of the managingDirector through the company  
16.    Float salary = (Float)bwComp.getPropertyValue("managingDirector.salary");  

  看起来麻烦了许多,但是这样Spring就可以使用统一的方式来管理bean的属性了。

0
相关文章