Spring学习(六)管理Bean

(一)使用BeanWrapper管理Bean:

在org.springframework.beans包中,有两个非常重要的类,BeanWrapper及BeanWrapperImpl,BeanWrapper封装了bean的行为,提供了设置和获取属性值的功能.

1、修改HelloWorld,增加一个无参的构造器:

package com.gc.entity;

import java.util.List;

public class HelloWorld {

 private List msg;
 
 public HelloWorld() {
  
 }

 public List getMsg() {
  return msg;
 }

 public void setMsg(List msg) {
  this.msg = msg;
 }
}
2、TestHelloWorld:

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.FileSystemXmlApplicationContext;

import com.gc.action.EhHello;
import com.gc.impl.Hello;

public class TestHelloWorld {

 public static void main(String[] args) {
  /**使用BeanWrapper来设置和获取相关bean的信息*/
  try {
   //通过Class.forName()方法,获取类HelloWorld的一个实例
   Object object = Class.forName("hello").newInstance();
   //通过BeanWrapper来设定类HelloWorld的属性
   BeanWrapper beanWrapper = new BeanWrapperImpl(object);
   //根据类变量设定变量的值
                  beanWrapper.setPropertyValue("msg","helloworld");
                  beanWrapper.setPropertyValue("date",new Date());
                  //把刚才设定的值,根据变量名取出
                  System.out.println(beanWrapper.getPropertyValue("msg"));
  } catch (InstantiationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }
}

(二)使用BeanFactory管理Bean

BeanFactory实际上是实例化、配置和管理众多Bean的容器,这些Bean通常会彼此合作,从而产生依赖。

一个BeanFactory可以用org.springframework.beans.factory.BeanFactory.该接口有多个实现,最简单的是

org.springframework.beans.factory.xml.XmlBeanFactory.

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.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;

import com.gc.action.EhHello;
import com.gc.action.HelloWorld;
import com.gc.impl.Hello;

public class TestHelloWorld {

 public static void main(String[] args) {
  //使用BeanFactory的方式
  ClassPathResource resource = new ClassPathResource("config.xml");
  //通过XmlBeanFactory来解析配置文件
  XmlBeanFactory xml = new XmlBeanFactory(resource);
  HelloWorld  hell =(HelloWorld) xml.getBean("hello");
 }
}

(3)使用ApplicationContext方式管理Bean

ApplicationContext除了提供BeanFactory所有的功能外,还有一些其他的功能主要包括国际话、资源访问、事件传递。

猜你喜欢

转载自happyforever.iteye.com/blog/1496746
今日推荐