閱讀726 返回首頁    go 阿裏雲 go 技術社區[雲棲]


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"
"https://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <!--定義一個Bean-->
    <bean   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------


最後更新:2017-04-02 22:16:38

  上一篇:go Spring-管理Bean 使用BeanFactory管理Bean
  下一篇:go 淺談LBS在快遞行業的應用(上)