在Spring容器中将Bean进行配置后,然后返回Bean对象实例叫做装配Bean。有两种方法:
1.BeanFactory(Bean工厂):
这种方法使用了org.springframework.beans.factory.BeanFactory接口获得Bean对象实例,常用的是org.springframwork.bean.factory.xml.XMLBeanFactory接口,通过XMLBeanFactory类,可以从xml配置文件中读取Bean的装配信息,并在Spring容器中建立并返回相应的JavaBean对象实例,在建立XMLBeanFactory对象实例前,需要将配置文件通过FileSystemResource对象传入XmlBeanFactory类的构造方法,并通过Bean工厂类的getBean方法获得Bean的对象实例:
//根据applicationContext.xml文件的内容创建BeanFactory对象 BeanFactory factory=new XmlBeanFactory(new FileSystemResource("src\\applicationContext.xml")); HelloService hello=(HelloService)factory.getBean("greeting");
2.ApplicationContext(应用上下文)
这种方式与BeanFactory类似,但是比BeanFactory提供了更多的功能,例如国际化、装载文件资源等,因此,如果要使用更多的功能,。建议使用该方法装配Bean
//装配applicationContext.xml文件 ApplicationContext context=new FileSystemXmlApplicationContext("src\\applicationContext.xml"); //从Spring配置文件中装配greeting,并将返回的对象转换成HelloService对象 HelloService hello=(HelloService)context.getBean("greeting");