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

spring在web工程和普通java工程使用时候区别

2016-03-10 17:40 507 查看
一、在web工程里,使用spring我们一般在web.xml里加

  <context-param>

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

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

    </context-param>

    <listener>

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

    </listener>

ContextLoaderListener 类大致方法如下

public class ContextLoaderListener extends ContextLoader implements ServletContextListener{

//主要也就是容器的初始化和销毁方法

}

ContextLoaderListener实现了ServletContextListener接口,ServletContextListener接口有两个方法,容器初始化和销毁

   public void contextInitialized ( ServletContextEvent sce );

   public void contextDestroyed ( ServletContextEvent sce );

ServletContextEvent 里面有获取ServletContext的方法,即一个Servlet的上下文,最后由ContextLoader初始化一个web工程的上下文,需要传递Servlet的上下文。

我们需要使用的bean,在容器初始化的时候也默认被初始化了,我们只需要在被管理的类里加一个setter方法就可以获取了。

二、在普通的java 工程中,通常用如下的代码来获取被管理的bean

1.取得一个上下文容器对象

ApplicationContext ac = new FileSystemXmlApplicationContext(“applicationContext.xml”);

2.从容器里面获取被管理的对象

ac.getBean(“beanName”);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: