美文网首页Java 杂谈Java程序员们的(家)
Spring之服务器启动加载bean.xml

Spring之服务器启动加载bean.xml

作者: 传奇内服号 | 来源:发表于2018-09-12 15:25 被阅读3次

1.创建 Service ,Dao,bean.xml

MyService.java

packagezh.spring.service;

importjavax.annotation.Resource;

importzh.spring.dao.MyDao;

publicclassMyService{

@Resource(name="myDao")

privateMyDao myDao;

publicvoiddao(){

myDao.dao();

}

}

Dao.java

packagezh.spring.dao;

publicclassMyDao{

publicvoiddao(){

System.out.println("dao...");

}

}

在src下创建bean.xml。

bean.xml

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

xsi:schemaLocation="

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

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

2. 创建Action和struts.xml

MyAction.java

packagezh.struts.action;

importorg.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

importzh.spring.service.MyService;

importcom.opensymphony.xwork2.ActionSupport;

publicclassMyActionextendsActionSupport{

@Override

publicStringexecute()throwsException{

ApplicationContext applicationContext =newClassPathXmlApplicationContext("bean.xml");

MyService myService = (MyService) applicationContext.getBean("myService");

myService.dao();

returnNONE;

}

}

在src下创建struts.xml。

struts.xml

"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"

"http://struts.apache.org/dtds/struts-2.3.dtd">

3.配置web.xml

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">

index.jsp

struts2

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

struts2

/*

4.测试

服务器启动时,不加载bean.xml。

而是,每访问一次:http://localhost:8080/Spring1/myAction.action,就加载一次bean.xml。

实际开发中,要求bean.xml只被加载一次。

解决:服务器启动时,会创建ServletContext,ServletContextListener监听器可以监听到ServletContext对象的创建。

因此,在web.xml中注册ServletContextListener监听器,在监听器里面加载bean.xml,将创建的对象存储于域对象。

5.服务器启动时加载bean.xml

Sping已经解决了上述问题,只需要在web.xml中配置 ContextLoaderListener 即可。

web.xml

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">

index.jsp

struts2

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

struts2

/*

org.springframework.web.context.ContextLoaderListener

contextConfigLocation

classpath:bean.xml

启动服务器,发现已经加载过了bean.xml。

相关文章

网友评论

    本文标题:Spring之服务器启动加载bean.xml

    本文链接:https://www.haomeiwen.com/subject/trnvgftx.html