Spring-管理Bean 使用BeanWrapper管理Bean

使用BeanWrapper管理Bean
1.修改Bean,增加一个无参数的构造函数
2.配置文件基本不需要改变
3.修改测试代码


Bean如下所示:

package com.gc.action;

import java.util.Date;

public class HelloWorld 
//implements InitializingBean,DisposableBean
{

	private String msg=null;//该变量用来存储字符串
	private Date date=null;//该变量用来存储日期
	
    public HelloWorld(){
    	
    }
	
	
	//设定变量msg的set方法
	public void setMsg(String msg) {
		this.msg=msg;
	}
	
	//获取变量msg的get方法
	public String getMsg() {
		return this.msg;
	}

	public Date getDate() {
		return this.date;
	}

	public void setDate(Date date) {
		this.date = date;
	}


	
}


配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <!--定义一个Bean-->
    <bean id="HelloWorld" class="com.gc.action.HelloWorld" init-method="afterPropertiesSet" destroy-method="cleanup">
    <!--将其变量msg通过依赖注入-->
 

    
    </bean>
    

</beans>


测试程序:

package com.gc.test;

import java.util.Date;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.gc.action.HelloWorld;


public class TestHelloWorld {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException
    {
    	//通过Class.forName()方法获取类HelloWorld的一个实例
    	Object obj=Class.forName("com.gc.action.HelloWorld").newInstance();
    	
    	//通过BeanWrapper来设定类HelloWorld的属性
    	BeanWrapper bw=new BeanWrapperImpl(obj);
    	
    	//根据类变量设定变量的值
    	bw.setPropertyValue("msg","HelloWorld");
    	bw.setPropertyValue("date",new Date());
    	
    	
    	System.out.println(bw.getPropertyValue("date")+" "+bw.getPropertyValue("msg")+"------");
    }
}



输出:

Tue Mar 20 19:29:35 CST 2012 HelloWorld------


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值