1、导入Spring相关jar包
spring.jar、commons-logging.jar
2、在WEB-INF下,新建applicationContext.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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="loginService" class="com.yd4.struts2.service.impl.LoginServiceImpl"></bean>
<bean id="loginAction" class="com.yd4.struts2.action.LoginAction" scope="prototype">
<property name="loginService" ref="loginService"></property>
</bean>
</beans>
3、在web.xml中配置Spring监听器
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
4、测试
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
LoginServiceImpl bean = (LoginServiceImpl) ctx.getBean("loginService");
// 调用bean方法
}
}
其他:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/applicationContext-aop.xml
classpath:/applicationContext-core.xml
</param-value>
</context-param>
配置该参数,则会加载WEB-INF下指定文件;不配置,默认加载WEB-INF下applicationContext.xml。
2、ClassPathXmlApplicationContext和FileSystemXmlApplicationContext区别
ClassPathXmlApplicationContext:只能读取存放在WEB-INF/classes目录下的配置文件;使用file:前缀,可以指定绝对路径。
FileSystemXmlApplicationContext:没有盘符,是项目工作路径,即项目根目录;有盘符,表示文件绝对路径。如果要使用classpath路径,需要前缀classpath:
示例:
// 绝对路径
new FileSystemXmlApplicationContext("F:/workspace/example/src/appliationContext.xml");
new ClassPathXmlApplicationContext("file:F:/workspace/example/src/appliationContext.xml");
new FileSystemXmlApplicationContext("file:F:/workspace/example/src/appliationContext.xml");
// classpath路径
new ClassPathXmlApplicationContext("appliationContext.xml");
new ClassPathXmlApplicationContext("classpath:appliationContext.xml");
new FileSystemXmlApplicationContext("classpath:appliationContext.xml");
// 没有盘符
new FileSystemXmlApplicationContext("WEB-INF/appliationContext.xml");