上一次初次做了mybatis框架的实验,这一次新学习了spring框架,就来整合整合!搞起来!!
一、实验目标:
1.1 巩固本章所学:重点掌握Spring IOC、AOP、事务等知识点
二、实验条件:
2.1 硬件条件:CPU i5以上、内存4g以上;
2.2 软件条件:IDEA、JDK1.8以上、Spring 5.x,mybatis 3.x、MySQL 5.5以上
三、实验内容:
整合Spring与Mybatis实现转账流程,具体要求:
3.1 数据源采用第三方Druid进行配置;(25分)
3.2 转账过程需要实现声明式注解事务功能;(25分)
3.3 所有的service、dao、datasource等需Spring容器管理;(25分)
3.4 利用AOP技术统计转账业务方法执行时间,打印在控制台即可。(25分)
四、实验过程
-----------------------------------------------------------4.1准备工作-----------------------------------------------------------
首先当然是要建库建表、新建项目、导包、配置日志文件啦!!一步一步来:
4.1.1建名为web的数据库、account表,编几个进去
4.1.2新建java项目及相关接口、包类
4.1.3导包注入灵魂
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.dgut</groupId>
<artifactId>springMVC</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>springMVC Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<!--mybatis包-->
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.6.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.6.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ua.com.lavi</groupId>
<artifactId>komock-core</artifactId>
<version>1.10.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>springMVC</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.1.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.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</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>
4.1.4配置日志文件
为了让我们的输出更加直观,显示更加完美,我们需要配置一下日志文件,网上有很多的啦!
log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
好啦!建完数据库和表,架好了项目框架,导好了所需要的包,也配置了日志文件,现在开始大动干戈地配置代码了!
-----------------------------------------------------------4.2类与接口----------------------------------------------------------
如何看懂一个项目:类——接口——映射,所以接下来一一列出每一层的配置,先从类和接口开始。
Account类
package com.dgut.domain;
public class Account {
private Integer id;
private String name;
private double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String
toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
AccountMapper接口
package com.dgut.dao;
import com.dgut.domain.Account;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;
@Repository
public interface AccountMapper {
/**
* 根据id查找用户
* @param id
* @return
*/
@Select("select * from account where id = #{id}")
public Account findById(Integer id);
/**
* 根据姓名查找用户
* @param name
* @return
*/
@Select("select * from account where name = #{name}")
public Account findByName(String name);
/**
* 根据姓名实现转账功能
* @param account
* @return
*/
@Update("update account set money=#{money} where name=#{name}")
public int updateAccount(Account account);
}
----------------------------------------------------------4.3配置业务层----------------------------------------------------------
配置好类与接口之后,着手业务层,转账的功能这类业务在这层。
AccountService
package com.dgut.service;
import com.dgut.domain.Account;
public interface AccountService {
public Account findbyid(Integer id);
/**
* 转账业务
* @param from 转账人
* @param to 接收人
* @param money 转账金额
*/
public void trans(String from, String to, Float money);
}
AccountServiceImpl
package com.dgut.service;
import com.dgut.dao.AccountMapper;
import com.dgut.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AccountServiceImpl implements AccountService{
@Autowired
private AccountMapper accountMapper;
public Account findbyid(Integer id) {
System.out.println("findbyid");
return accountMapper.findById(1);
}
@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
public void trans(String from, String to, Float money) {
//1.查找转账人是否存在
Account fromaccount = accountMapper.findByName(from);
if (fromaccount == null){
System.out.println("转账人不存在");
return;
}
//2.查找接收人是否存在
Account toaccount = accountMapper.findByName(to);
if(toaccount == null){
System.out.println("接收人不存在");
return;
}
//3.转账
System.out.println("转账中....");
fromaccount.setMoney((float) (fromaccount.getMoney()-money));
toaccount.setMoney((float) (toaccount.getMoney()+money));
accountMapper.updateAccount(fromaccount);
accountMapper.updateAccount(toaccount);
}
}
------------------------------------------------------------4.4配置文件------------------------------------------------------------
与数据库连接、spring容器加载后⾃动扫包,将有已注解的类,如@Service,@Repository纳⼊spring容器管理这些功能,都在这里实现。
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:mybatis="http://mybatis.org/schema/mybatis-spring"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd http://www.springframework.org/schema/context https://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 https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--spring管理数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/web?serverTimezone=UTC&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!--spring容器加载后⾃动扫包,扫到有注解的类(如:@Service,@Repository)则纳⼊spring容器管理-->
<context:component-scan base-package="com.dgut" />
<bean id="AccountMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.dgut.dao.AccountMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务-->
<!-- 配置一个事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入DataSource -->
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 开启注解AOP-->
<aop:aspectj-autoproxy/>
</beans>
------------------------------------------------------------4.5最后配置-------------------------------------------------------------
Mylog
package com.dgut.advice;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Aspect
@Component
public class MyLog {
@Around("execution(* com.dgut.service.AccountService.trans(..))")
public Object logPerformance(ProceedingJoinPoint pjp) throws Throwable {
SimpleDateFormat dst = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
System.out.println("转账开始时间" + dst.format(new Date()));// new Date()为获取当前系统时间
long start = System.currentTimeMillis();
Object obj = null;
try {
obj = pjp.proceed();
}
catch (Throwable e) {
e.printStackTrace();
}
SimpleDateFormat dend = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("转账结束时间" + dst.format(new Date()));
long end = System.currentTimeMillis();
System.out.println(pjp.getSignature().getName()+ "执行了"+(end-start)+"毫秒");
return obj;
}
}
Accountcontroller
package com.dgut.controller;
import com.dgut.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
@Controller
public class AccountController {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = (AccountService) applicationContext.getBean("accountServiceImpl");
accountService.trans("中国银行","农业银行", (float) 20);
}
}
-----------------------------------------------------------五、运行测试-----------------------------------------------------------
5.1输入一个不存在的银行
5.2正确输入的银行
测得转账业务方法执行了245毫秒。
✿✿ヽ(°▽°)ノ✿
✿✿ヽ(°▽°)ノ✿
✿✿ヽ(°▽°)ノ✿
此次spring整合mybatis之旅完结撒花!✿✿ヽ(°▽°)ノ✿
学会了springIOC、AOP、事务的相关知识!比理论知识更容易理解啦✿✿ヽ(°▽°)ノ✿
睡觉了下期再见✿✿ヽ(°▽°)ノ✿
青春有你2!
青春有你2!
青春有你2!
pick乃万✿✿ヽ(°▽°)ノ✿乃万✿✿ヽ(°▽°)ノ✿乃万✿✿ヽ(°▽°)ノ✿乃万✿✿ヽ(°▽°)ノ✿乃万✿✿ヽ(°▽°)ノ✿