乱花渐欲迷人眼,浅草才能没马蹄。
折腾一晚上,问题总算时解决了。心里倒是没有多舒服,真相有时候还蛮伤人的。
前几天,面试时,跟两个项目经理聊起来几个技术实际应用和底层原理。一位老哥指着项目组的人说“你看看这些人,你让他做,他也能做。可你问他为什么这样做,没几个能说明白的。“。“我问你原理有什么用,没用,就是看看你对这个事情的理解。”
基于这样的情况,我决定把几个事故多发地着重关注一下。
先从全家桶基石的两大核心下手。
昨天跟蛋蛋哥哥,说起来AOP的几种应用,突然间来了兴致。
开发工具:idea+maven+ssm
需求:使用aop实现日志打印功能,对controller种的操作进行记录。
1.首先创建项目:File-new-project-maven
finish,完成,等待maven依赖加载完。
2.创建相关的包,完善项目结构。以下为初始项目结构:
之后建立相关的包,然后再File-ProjectStructure中指定各文件属性。
3.数据库脚本如下(脚本附件不知道怎么添加,下边sql早数据库执行即可):
/*
SQLyog Ultimate v9.62
MySQL - 5.5.55
/
/!40101 SET NAMES utf8 */;
create table user (
id int (11),
name varchar (60),
age int (11),
sex varchar (30)
);
insert into user (id, name, age, sex) values(‘1’,‘蛋蛋’,‘22’,‘男’);
insert into user (id, name, age, sex) values(‘2’,‘山山’,‘21’,‘男’);
4.各种类的代码
创建各种类,不详细展开了。
实体类:
package com.scbg.pojo;
/**
*
* Author:三层饼干儿
* Date :2019-07-27
*/
public class User {
private int id;
private String name;
private int age;
private String sex;
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
Dao层接口:
package com.scbg.mapper;
import com.scbg.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
*
* Author:三层饼干儿
* Date :2019-07-27
*/
public interface UserMapper {
List<User> getUser(@Param("param") Map map);
void insertUser(@Param("param") Map param);
List<User> selectAll();
void update(@Param("param") Map param);
}
service
package com.scbg.service;
import com.scbg.pojo.User;
import java.util.List;
/**
*
* Author:三层饼干儿
* Date :2019-07-27
*/
public interface UserService {
List<User> getUser(int id);
void insertUser(int id, String name, int age, String sex);
List<User> selectAll();
Object update();
}
service.impl
package com.scbg.service.impl;
import com.scbg.mapper.UserMapper;
import com.scbg.pojo.User;
import com.scbg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* Author:三层饼干儿
* Date :2019-07-27
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
public List<User> getUser(int id) {
Map map = new HashMap();
map.put("id",id);
List<User> user = userMapper.getUser(map);
System.out.println(user+"--------------------------");
return user;
}
public void insertUser(int id, String name, int age, String sex) {
Map param = new HashMap();
param.put("id",id);param.put("name",name);
param.put("age",age);param.put("sex",sex);
userMapper.insertUser(param);
}
public List<User> selectAll() {
return userMapper.selectAll();
}
public Object update() {
Map param = new HashMap();
param.put("total",10);
param.put("name","测试一");
userMapper.update(param);
return "OK";
}
}
Controller
package com.scbg.controller;
import com.scbg.pojo.User;
import com.scbg.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
*
* Author:三层饼干儿
* Date : 2019-07-27
*/
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
Logger log = Logger.getLogger(UserController.class);
@RequestMapping("select")
@ResponseBody
public Object userTest(int id){
System.out.println("测试成功~~"+id);
List<User> user = userService.getUser(id);
log.info(user);
return user;
}
@RequestMapping("addUser")
public Object insertUser(int id,String name,int age,String sex){
userService.insertUser(id,name,age,sex);
return "OK";
}
@RequestMapping("selectAll")
public Object selectAll(){
return userService.selectAll();
}
@RequestMapping("update")
public Object update(){
return userService.update();
}
}
切面
package com.scbg.interceptor;
//增加maven依赖wl
//import org.apache.logging.log4j.LogManager;
import org.aspectj.lang.JoinPoint;
import org.springframework.stereotype.Component;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.slf4j.LoggerFactory;
/**
*
* Author:三层饼干儿
* Date :2019-07-27
*/
@Component
public class LogInterceptor {
/**
* 因为我这引入的是slf4j与log4j的桥接包,即可用log4j也可用slf4j输出日志
* log4j:
* import org.apache.logging.log4j.LogManager;
* import org.apache.logging.log4j.Logger;
* slf4j:
* import org.slf4j.Logger;
* import org.slf4j.LoggerFactory;
*/
// private static final Logger logger = LogManager.getLogger(LogInterceptor.class);
// private static final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
protected org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(this.getClass());
String logStr=null;
//前置通知
public void before(JoinPoint jp){
System.out.println("==========aaaaaaaaaaaaaa");
logStr=jp.getTarget().getClass().getName()+"类的"
+jp.getSignature().getName()+"方法开始执行******Start******";
log.debug(logStr);
System.out.println("---------------------before执行完了");
}
//最终通知
// public void after(JoinPoint jp){
// logStr=jp.getTarget().getClass().getName()+"类的"
// +jp.getSignature().getName()+"方法执行结束******End******";
// logger.info(logStr);
// }
// //异常抛出后通知
// public void afterThrowing(JoinPoint call){
// String className = call.getTarget().getClass().getName();
// String methodName = call.getSignature().getName();
// System.out.println(className+"."+methodName+"()方法抛出了异常...");
// }
// //后置通知
// public void afterReturn(JoinPoint call){
// String className = call.getTarget().getClass().getName();
// String methodName = call.getSignature().getName();
// System.out.println(className+"."+methodName+"()方法正常执行结束...");
// }
//用来做环绕通知的方法可以第一个参数定义为org.aspectj.lang.ProceedingJoinPoint类型
/*public Object around(ProceedingJoinPoint call) throws Throwable {
Object result = null;
//取得类名和方法名
String className = call.getTarget().getClass().getName();
String methodName = call.getSignature().getName();
//相当于前置通知
logStr=className+"类的"+methodName+"方法开始执行******Start******";
logger.info(logStr);
try {
result = call.proceed();
//相当于后置通知
logStr=className+"."+methodName+"()方法正常执行结束...";
logger.info(logStr);
} catch (Throwable e) {
//相当于异常抛出后通知
StackTraceElement stackTraceElement= e.getStackTrace()[e.getStackTrace().length-1];
Object[] args=call.getArgs();
logger.error("----------------------------------------------------------------------------------");
logger.error ( "===执行{}类的{}()方法的{}行",className,methodName,stackTraceElement.getLineNumber());
logger.error("===异常信息为:{} ",e.fillInStackTrace().toString());
logger.error("===参数信息为:{} ",args);
throw e;
}finally{
//相当于最终通知
logStr=className+"类的" +methodName+"方法执行结束******End******";
logger.info(logStr);
}
return result;
}
*/
}
5.各种配置文件:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.scbg</groupId>
<artifactId>SSMAOP</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>SSMAOP Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<!--spring版本号,5.0.0RELEASE是2017年9月发布的新版本-->
<spring.version>4.3.1.RELEASE</spring.version>
<!--mybatis版本号,3.4.5是2017年8月发布的新版本-->
<mybatis.version>3.4.5</mybatis.version>
<!--<slf4j.version>1.7.25</slf4j.version>-->
<slf4j.version>1.7.25</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--spring核心包——Start-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!--spring核心包——End-->
<!--MyBatis核心包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.6</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.3.8</version>
</dependency>
<!--mybatis/spring包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--javaEE版本8.0-->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
<!--mysql数据库的jdbc连接包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--新版本使用最多的是6.0.6 但在我的配置中无法使用该版本,报一个很无解的异常-->
<version>5.1.39</version>
</dependency>
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!--jstl标签包-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--日志文件管理包——logStart-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
<!--<scope>test</scope>-->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--日志文件管理包——logEnd-->
<!--格式化对象,方便输出日志-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.42</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!--文件上传组件包-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
<!--AOP start-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.8</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.2</version>
</dependency>
<!--AOP end-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>2.10.0</version>
<scope>runtime</scope>
</dependency>
<!--wl-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.4</version>
</dependency>
</dependencies>
<build>
<finalName>SSMAOP</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<!-- 指定spring文件名称及路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-*.xml</param-value>
</context-param>
<!-- 注册前端控制器 -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 日志记录 -->
<context-param>
<!-- 日志配置文件路径 -->
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:config/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>
<!--log4j日志监听 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<filter>
<filter-name>log4jServletFilter</filter-name>
<filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>log4jServletFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
<!--spring和mybatis的配置文件-->
<!--<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/config/spring-mybatis.xml</param-value>
</context-param>-->
<!--spring监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--防止spring内存溢出监听器-->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 注册字符编码过滤器 -->
<!--<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>-->
<!--需要访问js文件时使用-->
<!--<servlet-mapping>-->
<!--<servlet-name>default</servlet-name>-->
<!--<url-pattern>*.js</url-pattern>-->
<!--</servlet-mapping>-->
</web-app>
log4j.properties
log4j.rootLogger = DEBUG,Console,File
#设置日志输出级别和目的地
#log4j.appender.appenderName日志输出位置命名
#控制台
log4j.appender.Console = org.apache.log4j.ConsoleAppender
#指定输出控制台
log4j.appender.Console.Target = System.out
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern = %5p %d %C: %m%n
#每天打印一个日志文件
#速出到文件,每天产产生一个文件
log4j.appender.File = org.apache.log4j.DailyRollingFileAppender
#输出文件的路径
log4j.appender.File.File=W:/SSMAOP.log
log4j.appender.File.Encoding=UTF-8
log4j.appender.File.ImmediateFlush=true
#打印所有级别的日志信息
#日志消息输出的最低层次
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =%d{ABSOLUTE} %5p %c{1}\:%L - %m%n
log4j.logger.com.opensymphony=ERROR
log4j.logger.org.springframework=ERROR
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=INFO
log4j.logger.java.sql.PreparedStatement=INFO
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.java.sql.Statement=INFO
jdbc.properties
#开发环境
jdbc.driver=com.mysql.jdbc.Driver
#数据库还没有创建
jdbc.url=jdbc:mysql://localhost:3306/~~自己的数据库名~~
jdbc.user=~~写自己的~~
jdbc.password=~~写自己的~~
spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
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-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 注册组件扫描器 -->
<!--<context:component-scan base-package="com.scbg.controller"></context:component-scan>-->
<context:component-scan base-package="com.scbg.controller">
<!--<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
</context:component-scan>
<!-- 注解驱动 -->
<mvc:annotation-driven/>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="logInterceptor" class="com.scbg.interceptor.LogInterceptor"/>
<aop:config proxy-target-class="true"/>
<aop:config>
<aop:pointcut expression="execution(* *..controller.*.*(..))" id="logPointCut"/>
<!--定义切面-->
<aop:aspect ref="logInterceptor">
<!--定义切入点-->
<!--方法执行之前被调用执行的-->
<!--<aop:before method="before" pointcut-ref="logPointCut"/><!–一个切入点的引用–>-->
<!--<aop:after method="after" pointcut-ref="logPointCut"/><!–一个切入点的引用–>-->
<!--<aop:after-throwing method="afterThrowing" pointcut-ref="logPointCut" />-->
<!--<aop:after-returning method="afterReturn" pointcut-ref="logPointCut" />-->
<aop:before method="before" pointcut-ref="logPointCut"/>
</aop:aspect>
</aop:config>
<aop:aspectj-autoproxy/>
</beans>
spring.mybatis.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:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--加载配置文件-->
<context:property-placeholder location="classpath:config/jdbc.properties"/>
<!--配置数据源-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--spring和mybatis整合-->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.scbg.pojo"/>
<property name="mapperLocations" value="classpath*:mapper/**/**Mapper.xml"/>
<!--<property name="configLocation" value="classpath:config/mybatis-config.xml"/>-->
</bean>
<!--扫描mapper接口包-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.scbg.mapper"/>
<property name="sqlSessionFactoryBeanName" >
<idref bean="SqlSessionFactory"/>
</property>
</bean>
<!--service实现类扫描-->
<!--<context:component-scan base-package="com.scbg.service"/>-->
<!--<tx:advice id="defaultTransactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!–<tx:method name="*" isolation="DEFAULT"–>
<!–propagation="REQUIRED" no-rollback-for="java.lang.RuntimeException" timeout="100"/>–>
<!–<tx:method name="*" read-only="true"/>–>
<!– 以方法为单位,指定方法应用什么事务属性 isolation:隔离级别 propagation:传播行为 read-only:是否只读 –>
<!–PROPAGATION_REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。–>
<!–PROPAGATION_SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。–>
<!–PROPAGATION_MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。–>
<!–PROPAGATION_REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。–>
<!–PROPAGATION_NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。–>
<!–PROPAGATION_NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。–>
<!–PROPAGATION_NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。–>
<tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="Borrow*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="add*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="merge*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="del*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="remove*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="put*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
<tx:method name="use*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
</tx:attributes>
</tx:advice>-->
<!--aop全局事务管理(下面基于controller层)-->
<!-- <aop:config>
<aop:pointcut id="allControllerMethods"
expression="execution(* com..controller..*(..))"/>
<aop:advisor advice-ref="defaultTransactionAdvice"
pointcut-ref="allControllerMethods"/>
</aop:config>-->
<!--注册切面类-->
<!--<bean id="userController" class="com.scbg.controller.UserController"/>-->
<!--<bean id="aopServerAspectj" class="com.scbg.aop.AopServerAspectj"/>-->
<!--事务管理-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
spring-service.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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册组件扫描器 -->
<context:component-scan base-package="com.scbg.service.impl"></context:component-scan>
</beans>
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.scbg.mapper.UserMapper">
<select id="getUser" parameterType="java.util.Map" resultType="com.scbg.pojo.User">
SELECT *
FROM user
where id =#{param.id}
</select>
<insert id="insertUser" parameterType="java.util.Map">
INSERT INTO user (id,name,age,sex) values(#{param.id},#{param.name},#{param.age},#{param.sex})
</insert>
<select id="selectAll" resultType="com.scbg.pojo.User">
SELECT * FROM USER
</select>
<update id="update" parameterType="java.util.Map">
UPDATE USER SET id=id-#{param.total},age=age+#{param.total}
WHERE name=#{param.name}
</update>
</mapper>
aop类没有用到,就不说了。(我刚开始参考的一个博主的代码,但是项目没跑起来,最终放弃了)
6.配置tomcat
运行项目。在url中输入访问信息,回车,出现信息。查看控制台。
成了,哈哈哈,开心不。