在Spring中,Bean的管理主要有3种方法,分别是使用BeanWrapper管理Bean、使用BeanFactory管理Bean和使用ApplicationContext管理Bean。
1、使用BeanWrapper管理Bean
在org.springframework.beans包中,还有两个非常重要的类:BeanWrapper接口及它的实现BeanWrapperImpl。BeanWrapper封装了一个Bean的行为,提供了设置和获得属性值的功能。通过BeanWrapper可以获得Bean的属性和描述、查询只读或者可写属性。
下面通过BeanWrapper来实现输出HelloWorld,其实现思路是:
----HelloWord.java----
import java.util.Date;
public class HelloWorld{
private String msg = null;
private Date date = null;
public helloWorld(){
}
public void setMsg(String msg){
this.msg = msg;
}
public String getMsg(){
return this.msg;
}
public void setDate(Date date){
this.date = date;
}
public Date getDate(){
return this.date;
}
----测试程序TestHelloWorl.java-----
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.context.ApplicationContext;
public class TestHelloWorld{
public static void main(String[] args)throws InstantiationExceptoin,IllegalAccessException,ClassNotFoundException{
Object obj = Class.forName("HelloWorld").newInstance();
BeanWrapper bw = new BeanWrapperImpl(obj);
bw.setPropertyValue('msg',"HellowWorld");
bw.setPropertyValue("date",new Date());
System.out.println(bw.getPropertyValue("date")+""+bw.getPropertyValue("msg"));
}
}
1、使用BeanWrapper管理Bean
在org.springframework.beans包中,还有两个非常重要的类:BeanWrapper接口及它的实现BeanWrapperImpl。BeanWrapper封装了一个Bean的行为,提供了设置和获得属性值的功能。通过BeanWrapper可以获得Bean的属性和描述、查询只读或者可写属性。
下面通过BeanWrapper来实现输出HelloWorld,其实现思路是:
----HelloWord.java----
import java.util.Date;
public class HelloWorld{
private String msg = null;
private Date date = null;
public helloWorld(){
}
public void setMsg(String msg){
this.msg = msg;
}
public String getMsg(){
return this.msg;
}
public void setDate(Date date){
this.date = date;
}
public Date getDate(){
return this.date;
}
----测试程序TestHelloWorl.java-----
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.context.ApplicationContext;
public class TestHelloWorld{
public static void main(String[] args)throws InstantiationExceptoin,IllegalAccessException,ClassNotFoundException{
Object obj = Class.forName("HelloWorld").newInstance();
BeanWrapper bw = new BeanWrapperImpl(obj);
bw.setPropertyValue('msg',"HellowWorld");
bw.setPropertyValue("date",new Date());
System.out.println(bw.getPropertyValue("date")+""+bw.getPropertyValue("msg"));
}
}