其实也就那么几步:添加jar包;写配置文件;写相应的java类。当然,如果 需要和Struts2.0集成,还是有几个地方需要多加注意的。

1、jar包

可以单独加Spring-web.jar、Spring-aop.jar这些包,也可以加一个总包Spring.jar。只要包含需要用到的类就 行。

如果需要Spring和Struts2.0集成,记得加上struts2-spring-plugin.jar。

2、写配置文件

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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

<bean id="BASIC" class="common.action.BasicAction"></bean>

</beans>

如果与Struts集成,记得在web.xml里写上,声明由Spring来做类管理

<!-- 以下是Spring的监听器定义 -->
<listener>
   <listener-class>
    org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener>
<!-- 以上是Spring的监听器定义 -->

还可以加一行,定义applicationContext.xml的位置或名称。*是通配符。

<!-- 以下是Spring配置文件位置的定义 -->
   <context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>
    /WEB-INF/classes/applicationContext_*.xml
   </param-value>
</context-param>
<!-- 以上是Spring配置文件位置的定义 -->

3、java类

java类的编写只有一条需要注意:要通过Spring来注入的属性,需要在类中写明getter和setter方法。比如 applicationContext.xml中定义了:

<bean id="BASIC" class="common.action.BasicAction">
   <property name="errorbean" ref="eb"/>
</bean>

<bean id="eb" class="common.bean.ErrorBean"></bean>

在BasicAction.java中就必须要有如下定义,否则Spring是要报错的。

private ErrorBean errorbean;


public ErrorBean getErrorbean() {
   return errorbean;
}

public void setErrorbean(ErrorBean errorbean) {
   this.errorbean = errorbean;
}

按上述步骤配置好之后,Spring的ioc功能应该是可以正常使用了。其它方面,如aop等,另外记录吧。