TA的每日心情  | 开心 2021-3-12 23:18 | 
|---|
 
  签到天数: 2 天 [LV.1]初来乍到  
 | 
 
| 
 
 Core模块主要的功能是实现了反向控制(Inversion of Control)与依赖注入DI(Dependency Injection),Bean配置以及加载。Core模块中有Beans,BeanFactory,BeanDefinitions,ApplicationContext等几个重要概念。 
   Beans为Spring里的各种对象,一般要配置在Spring配置文件中;BeanFactory为创建Beans的Factory,Spring通过BeanFactory加载各种Beans;BeanDefinition为Bean在配置文件中的定义,一般要定义id为class;ApplicationContext代表配置文件。 
   这些类都位于org.springframework.beans和org.springframework.context中。这是Spring最核心的包。Core模块依赖于Spring的Core类库。 
BeanFactory工厂 
BeanFactory是实例化,配置,管理众多Bean的容器。这些Bean类一般是离散的,但在Spring中被配置为相互依赖。BeanFactory根据配置实例化Bean对象,并设置相互的依赖性。 
BeanFactory可用接口org.springframework.beans.factory.BeanFactory表示。BeanFactory有多种实现,最常用的为org.springframework.beans.factory.xml.XmlBeanFactory。XmlBeanFactory能加载XML格式的配置文件。 
1, 实例化BeanFactory 
  在web程序中用户不需要实例化BeanFactory,Web程序加载的时候会自动实例化BeanFactory,并加载所有的Beans,将各种Bean设置到各个Servlet中,struts的Action中,或者Hibernate资源中。开发者直接编写Servlet,Action,Hibernate相关的代码即可,无须操作BeanFactory。 
  在java桌面程序中,需要从BeanFactory中获取Bean,因此需要实例化BeanFactory,构造函数的参数为配置文件的路径。例如加载ClassPath下的配置文件可以用ClassPathResource加载,然后传递XmlBeanFactory构造函数。代码如下: 
  ClassPathResource res = new ClassPathResource(“applicationContext.xml”);//获取配置资源 
  XmlBeanFactory factory = new XmlBeanFactory(res); //获取对象工厂 
  Iservice hello = (IService)factory.getBean(“service”); //获取对象 
  … … //其它代码略 
  Factory.destorySingletons(); 
参数applicationContext.xml为ClassPath根目录下的文件。applicationContext.xml为Spring默认的配置文件名称,默认存储在ClassPath根目录下。或者使用文件流加载任意位置的配置文件,并传递给XmlBeanFactory构造函数,例如: 
   InputStream is = new FileInputStream(“c://ApplicationContext.xml”); //获取配置资源 
   XmlBeanFactory factory = new XmlBeanFactory(is); //获取对象工厂 
或者用ClassPathXmlApplicationContext加载多个配置文件(多个配置文件以字符串数组形式传入),并传递给XmlBeanFactory构造函数: 
  ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext( 
  New String[]{“applicationContext.xml”,”applicationContext-part2.xml”} 
); //多个配置 
BeanFactory factory = (BeanFactory)appContext; //ApplicationContext继承自BeanFactory接口 
2.         XmlBeanFactory配置格式 
一个BeanFactory中配置了多个Bean.在XmlBeanFactory中,配置文件的根节点为<beans>,里面定义了几个<bean>子节点,每个<bean>定义一个Bean。格式如下: 
<beans>  <!—Beans根节点 à 
  <bean id=”…” class=”…”> <!—Bean节点,定义Beanà 
  … … 
  <bean id=”…” class=”…”>  <!—Bean节点,定义Bean à 
     <property name=”…” value=”…”></property> <!—property定义属性 à 
     <property name=”…” ref=”…”></property>  <!—property定义属性à 
  </bean> 
</beans> 
<property/>表示将使用name属性对应的setter方法设置该属性。 |   
 
 
 
 |