Spring用到的jar包有:spring-beans-4.0.0.RELEASE.jar、spring-context-4.0.0.RELEASE.jar、spring-core-4.0.0.RELEASE.jar、spring-expression-4.0.0.RELEASE.jar、commons-logging-1.1.3.jar、com.springsource.net.sf.cglib-2.2.0.jar、com.springsource.org.aopalliance-1.0.0.jar、com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar、taglibs-standard-impl-1.2.1.jar、taglibs-standard-spec-1.2.1.jar,我的邮箱是1248726954@qq.com,可以找我要,或者找我的博客,有网址。
一、web.xml配置
在web.xml中新增Spring的监听器的相关配置并指定Spring的配置文件,代码如下:
<!-- 配置Spring的相关监听器,指定Spring的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/conf/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
WEB-INF/conf/applicationContext.xml为Spring配置文件的路径;
二、配置Spring的配置文件
1、注解扫描,扫描Controller以外的注解,代码如下:
<!-- 注解扫描 -->
<context:component-scan base-package="com.ssm.framework">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
2、配置事务管理器,在这里需要用到c3p0连接池,jar包为c3p0-0.9.1.2.jar,代码如下:
<!-- 连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl"
value="jdbc:mysql://127.0.0.1:3306/paperanalyse?useUnicode=true&characterEncoding=utf-8"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 事务 -->
<bean id="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 基于注解使用事务 -->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
三、测试
1、新建一个接口和一个类,目录结构如下图:

接口代码示例:
package com.ssm.framework.service;
import com.alibaba.fastjson.JSONObject;
public interface LoginService {
public JSONObject loginFun(JSONObject param);
}
Impl类代码示例:
package com.ssm.framework.service.Impl;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.ssm.framework.service.LoginService;
@Service
public class LoginServiceImpl implements LoginService{
@Override
public JSONObject loginFun(JSONObject param) {
JSONObject json = new JSONObject();
System.out.println(param);
json.put("success", true);
return json;
}
}
在Controller中需要使用@Autowoired(自动装配)注入Bean,代码如下:
@Autowired
private LoginService loginService;
@RequestMapping(value="loginAction", method=RequestMethod.POST)
@ResponseBody
public JSONObject login(@RequestBody JSONObject param, HttpServletRequest request) {
JSONObject json = loginService.loginFun(param);
return json;
}
控制台打印结果如下:

后续有新的理解会有补充。。。。。
本文详细介绍Spring框架的配置步骤,包括所需jar包、web.xml配置、Spring配置文件设置及事务管理,通过具体示例展示如何进行注解扫描、配置事务管理器及使用c3p0连接池。同时,提供接口与实现类的代码示例,演示如何在Controller中注入Bean进行测试。

被折叠的 条评论
为什么被折叠?



