spring心得2--bean的生命周期@Spring监听器的作用@Spring初始化容器案例分析@web项目使用

Scope的默认值是singleton,lazy-init的默认值是default,default相当于false

1.bean的生命周期

bean被载入到容器中时,他的生命周期就开始了。bean工厂在一个bean可以使用前完成很多工作:

1).容器寻找bean的定义信息并实例化。

2).使用依赖注入,spring按bean定义信息配置bean的所有属性。

3).若bean实现了BeanNameAware接口,工厂调用Bean的setBeanName()方法传递bean的ID。

4).若bean实现了BeanFactoryAware接口,工厂调用setBeanFactory()方法传入工厂自身。

5).若BeanPostProcessor和bean关联,则它们的 postProcessBeforeInitialization()方法被调用。

6).若bean指定了ini-method方法、,它将被调用。

7).最后,若有BeanPostProcessor和bean关联,则它们的postProcessAfterInitialization()方法被调用。

2.Spring监听器的作用

我们自动加载spring配置文件需要在web.xml文件中添加一段配置:

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value> classpath*:applicationContext-*.xml </param-value>

</context-param>

<listener>

<listener-class> 

org.springframework.web.context.ContextLoaderListener 

</listener-class>

</listener>

ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。至于ApplicationContext.xml这个配置文件部署在哪,如何配置多个xml文件,查看它的API文档,在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成。

查看API得知:ContextLoader可以由 ContextLoaderListener和ContextLoaderServlet生成。如果查看ContextLoaderServlet的API,可以看到它也关联了ContextLoader这个类而且它实现了HttpServlet这个接口;

ContextLoader创建的是 XmlWebApplicationContext这样一个类,它实现的接口是WebApplicationContext->ConfigurableWebApplicationContext->ApplicationContext-> BeanFactory这样一来spring中的所有bean都由这个类来创建。

如何部署applicationContext的xml文件,如果在web.xml中不写任何参数配置信息,默认的路径是"/WEB-INF/applicationContext.xml,在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml。如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数:

<context-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>

            /WEB-INF/classes/applicationContext-*.xml

        </param-value>

 </context-param>

     在<param-value> </param-value>里指定相应的xml文件名,如果有多个xml文件,可以写在一起并一“,”号分隔。上面的applicationContext-*.xml采用通配符,比如这那个目录下有applicationContext-ibatis-base.xml,applicationContext-action.xml,applicationContext-ibatis-dao.xml等文件,都会一同被载入

注意:

如果beans.xml文件放在src目录下,在生成ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");但若是applicationContext.xml必须放到WEB-INF下的Classes目录下,才能用ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");生成ApplicationContext,若是直接放到WEB-INF下会抛出异常说找不到applicationContext文件

3. Spring初始化容器 案例分析

package www.csdn.spring.test;

 

import java.beans.XMLDecoder;

 

import org.junit.Test;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.FileSystemResource;

import www.csdn.spring.service.HelloService;

import www.csdn.spring.service.impl.HelloServiceImpl;

 

publicclass FactoryTest {

 

   @Test

   publicvoid testFacory() {

      /*

       * Spring初始化容器.三种经常用到的实现:

       * 一、ClassPathXmlApplicationContext:从类路径中加载。

       * 二、FileSystemXmlApplicationContext:从文件系统加载。

       * 三、XmlWebApplicationContext:从web系统中加载。 InputStreamResource不能够使用了。

       * 特殊的例子:不能使用InputStreamResource

       * InputStreamResource res = new InputStreamResource(new

       * FileInputStream("D:\\Ncode\\mcode\\sday02\\src\\spring.xml"));

       * 

       * isOpen(){ return true;}

       */

 

      //下面所列举的案例都是使用bean工厂加载配置文件的几种案例,使用上下文的案例在上一篇博客的springHelloJava案例中已经介绍过了

      /*//方法一:FileSystemResource类的使用

      FileSystemResource fileResource = new FileSystemResource(

            "F:\\csdn-study\\MyWorkspace\\springHelloJava\\src\\spring.xml");

            

      //方法二:ClassPathResource类的使用

      ClassPathResource classResource = new ClassPathResource("spring.xml");

      BeanFactory factory = (BeanFactory) new XmlBeanFactory(classResource);     

       */

      

      //方法三:FileSystemXmlApplicationContext与ClassPathXmlApplicationContext的对比案例

      //BeanFactory factory = new FileSystemXmlApplicationContext("F:\\csdn-study\\MyWorkspace\\springHelloJava\\src\\spring.xml");

      

      ApplicationContext factory = new ClassPathXmlApplicationContext("classpath:spring.xml");

      

      HelloService helloservice = (HelloService) factory

            .getBean("helloServiceImpl",HelloServiceImpl.class);

      helloservice.sayHello();

   }

 

}

4.web项目使用spring的入门案例

    一下配置文件和类关键还是看注释,注释中有spring的注意事项以及犀利的知识点

spring.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans.xsd">

 

 

   <!-- spring容器就是负责创建、管理、维护Bean 并且能够依赖注入到相应组件上 -->

   <bean id="helloDaoImpl" class="www.csdn.spring.dao.impl.HelloDaoImpl" scope="singleton" lazy-init="default"></bean>

</beans>

Web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" 

   xmlns="http://java.sun.com/xml/ns/javaee" 

   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 

   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <display-name></display-name>

 

  <context-param>

     <param-name>contextConfigLocation</param-name>

     <!-- 这里的classpath路径是spring.xml在src路径下

     <param-value>classpath:spring.xml</param-value>

      -->

      <!-- 也可以像下面这种写法 -->

     <param-value>/WEB-INF/classes/www/csdn/spring/resource/spring.xml</param-value>

  </context-param>

  

  <listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  </listener>

 

  <servlet>

    <servlet-name>HelloServlet</servlet-name>

    <servlet-class>www.csdn.spring.servlet.HelloServlet</servlet-class>

  </servlet>

 

  <servlet-mapping>

    <servlet-name>HelloServlet</servlet-name>

    <url-pattern>/servlet/HelloServlet</url-pattern>

  </servlet-mapping>

  

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

</web-app>

 

HelloServlet类

package www.csdn.spring.servlet;

 

import java.io.IOException;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.springframework.web.context.WebApplicationContext;

import org.springframework.web.context.support.WebApplicationContextUtils;

import org.springframework.web.context.support.XmlWebApplicationContext;

 

import www.csdn.spring.dao.HelloDao;

import www.csdn.spring.dao.impl.HelloDaoImpl;

 

public class HelloServlet extends HttpServlet {

 

       public void doGet(HttpServletRequest request, HttpServletResponse response)

                     throws ServletException, IOException {

 

              doPost(request, response);

       }

 

       public void doPost(HttpServletRequest request, HttpServletResponse response)

                     throws ServletException, IOException {

 

              /*// 1.利用XmlWebApplicationContext对象加载

              XmlWebApplicationContext context = new XmlWebApplicationContext();

 

              

               * 默认的路径/WEB-INF/applicationContext.xml,applicationContext.xml文件名称

               * 可以任意起,比如我改成了spring.xml;

               * 位置也可以随便放,但是如果放到src下路径就应该写成/WEB-INF/classes/applicationContext.xml;

               * 放到某一包下,路径就应该写成对应classes加上包名,比如:

              

              //加载spring文件

              context.setConfigLocation("/WEB-INF/classes/www/csdn/spring/resource/spring.xml");

              //将servlet的上下文环境设置成spring的上下文环境

              context.setServletContext(getServletContext());

              //刷新容器

              context.refresh();

              HelloDao helloDao = (HelloDao) context.getBean("helloDaoImpl");

              helloDao.sayHello();

              // XmlWebApplicationContext context = new XmlWebApplicationContext();

 

              System.out.println("=======================");*/

              

              //2.利用WebApplicationContextUti对象加载

 

              //使用这种方式,spring不会默认的额加载spring配置文件,也不能像上面那种写法一样去写,这时要在web.xml配置一个监听器,写一个配置标签来指定spring配置文件的位置

              WebApplicationContext contexts = WebApplicationContextUtils

                            .getWebApplicationContext(getServletContext());

              HelloDao helloDaos = contexts.getBean("helloDaoImpl", HelloDaoImpl.class);

              helloDaos.sayHello();

 

       }

}


 

posted @ 2013-04-23 21:00  yangkai_keven  阅读(218)  评论(0编辑  收藏  举报