Spring中Bean的管理及ApplicationContext的使用

来源:互联网 发布:嗟乎,此真将军矣 编辑:程序博客网 时间:2024/06/05 19:32

(一)Spring中bean的管理方式一般有三种。

BeanWrapper、BeanFactory、ApplicationContext


1、BeanWrapper单独对bean进行操作,没有涉及配置文件。

BeanWrapper是一个几口,其实现类BeanWrapperImpl,BeanWrapperImpl的构造函数有传参数Object,所以用法如下:

public class HelloWorldTest {public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {Object obj = Class.forName("com.gc.acion.HelloWorld").newInstance();//实例化类HelloWorld//得到Bean的管理类BeanWrapper wapper = new BeanWrapperImpl(obj);//为bean赋值wapper.setPropertyValue("msg", "wangyj");wapper.setPropertyValue("date", new Date());System.out.println("msg="+wapper.getPropertyValue("msg"));System.out.println("date="+wapper.getPropertyValue("date"));}}

2、BeanFactory是一个接口,其实现类有XmlBeanFactory。XmlBeanFactory的构造函数传值resource,所以用法如下:

ClassPathResource resource = new ClassPathResource("config.xml");//获取配置文件XmlBeanFactory factory = new XmlBeanFactory(resource);//得到BeanFacotyHelloWorld helloWorld = (HelloWorld)factory.getBean("HelloWorld");//通过getBean的方法得到BeanSystem.out.println(helloWorld.getMsg()+helloWorld.getDate());

3、ApplicationContext是BeanFactory的超集。

ApplicationContext是一个接口,FileSystemXmlApplicationContext是ApplicationContext的实现类。

通过构造函数得到一个ApplicationContext,参数是configLocation。

ApplicationContext context = new FileSystemXmlApplicationContext("config.xml");HelloWorld helloWorld = (HelloWorld) context.getBean("HelloWorld");System.out.println(helloWorld.getMsg()+helloWorld.getDate());

(二)ApplicationContext的使用。




0 0