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


Spring-管理Bean 使用BeanFactory管理Bean

Bean:


package com.gc.action;

import java.util.Date;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.DisposableBean;

public class HelloWorld 
//implements InitializingBean,DisposableBean
{

	private String msg=null;//該變量用來存儲字符串
	private Date date=null;//該變量用來存儲日期
	


	
	public void afterPropertiesSet() {
		// TODO Auto-generated method stub
		this.msg="HelloWorld";
		this.date=new Date();
		System.out.println("2000");
	}
	
	
	public void cleanup() {
		// TODO Auto-generated method stub
		this.msg="";
		this.date=null;
	    System.out.println("您銷毀了msg"+this.msg+"和date"+this.date);  
	}
	
	public HelloWorld(String msg)
	{
		    this.msg=msg;	
	}
	
	public HelloWorld()//這個必須寫,否則不能轉到上麵的那個
	{
	    this.msg=msg;	
	}
	
	//設定變量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.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

import com.gc.action.HelloWorld;


public class TestHelloWorld {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException
    {
    	//通過ClassPathResource獲取配置文檔
    	ClassPathResource res=new ClassPathResource("config.xml");
    	
    	//通過XmlBeanFactory來解析配置翁當
    	XmlBeanFactory factory=new XmlBeanFactory(res);
    	
    	//根據id獲取Bean
    	HelloWorld helloWorld=(HelloWorld)factory.getBean("HelloWorld");
    	
    	//拿出Bean在配置文檔中設定的內容
    	System.out.println(helloWorld.getDate()+" "+helloWorld.getMsg()+"------");
    }
}





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

  上一篇:go Spring-事件傳遞
  下一篇:go Spring-管理Bean 使用BeanWrapper管理Bean