Spring学习笔记之bean和BeanFactory

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值