您的位置:首页 > 编程语言 > Java开发

Spring学习笔记之bean和BeanFactory

2017-03-09 22:49 465 查看
1、Spring容器的根接口:org.springframework.beansfactory.BeanFactory。Spring的任何容器实现类都会直接或间接的实现该接口。该接口的四种基本方法:

public boolean containsBean(String name);

public Object getBean(String name);

public Object getBean(String name,Class requiredType);

public Class getType(String name);

2、BeanFactory的常用实现类:org.springframework.beans.factory.xml.XmlBeanFactory;

3、对于大多数J2EE应用,推荐使用ApplicationContext,ApplicationContext的常用实现类为org.springframework.context.support.FileSystemXmlApplicationContext;

4、创建BeanFactory实例时,应提供xml配置文件作为参数,xml配置文件通常使用Resource对象传入。Resource 接口是Spring Bean配置支援的抽象,是所有配置资源的根接口。

5、大部分J2EE应用可以在启动web自动加载ApplicationContext实例,对于独立的应用程序,有如下两种实例化BeanFactory方法:方法1:

//以指定路径下的bean.xml配置文件作为参数,创建文件输入流
InputStream is=new FileInputStream("beans.xml");
//以指定的文件输入流 is ,创建Resource对象
InputStreamResource isr=new InputStreamResource(is);
//以Resource对象作为参数,创建BeanFactory实例
XmlBeanFactory factory=new XmlBeanFactory(isr);


方法二:

//搜索ClASSPATH路径,以CLASSPATH路径下的beans.xml文件创建Resource对象
ClassPathResource res=new ClassPathResource("beans.xml");
//以Resource对象为参数,创建BeanFactory实例
XmlBeanFactory factory=new XmlBeanFactory(res);


同时加载多个xml配置文件的配置方法:

//搜索CLASSPATH路径,以CLASSPATH路径下的applicationContext.xml、service.xml文件创建ApplicationContext
/***如果将ClassPathXmlApplicationContext类替换为FileSystemXmlApplicationContext实现类,可以从指定路径搜索特定文件加载***/
ClassPathXmlApplicationContext appContext= new ClassPathXmlApplicationContext(
new String[]{"applicationContext.xml","service.xml"});
//ApplicationContext是BeanFactory的子接口,支持强类型转换
BeanFactory factory=(BeanFactory)appContext;


6、Spring最简单的配置文件:

<!--XML文件头,指定XML文件的编码集-->
<?xml version="1.0" encoding="gb2312"?>
<!--指定Spring配置文件的dtd-->
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<!--beans元素是Spring配置文件的根元素,所有的Spring配置文件都应该按如下结构书写-->
<beans>
...
</beans>


7、bean实例化的三种方法:

1. 调用构造器构造bean实例

2. BeanFactory调用某个类的静态工厂方法创建bean

3. BeanFactory调用实例工厂方法创建bean
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: