SSM整合2
目录
目录结构
数据库
/*
Navicat Premium Data Transfer
Source Server : centos7_mysql
Source Server Type : MySQL
Source Server Version : 80015
Source Host : 192.168.234.128:3306
Source Schema : ssm
Target Server Type : MySQL
Target Server Version : 80015
File Encoding : 65001
Date: 11/11/2020 12:37:30
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`money` double NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 24 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES (1, '张三', 100);
INSERT INTO `account` VALUES (2, '哈哈', 200);
INSERT INTO `account` VALUES (3, '中国', 100);
INSERT INTO `account` VALUES (4, 'a', 100);
INSERT INTO `account` VALUES (5, 'b', 100);
SET FOREIGN_KEY_CHECKS = 1;
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.zjw</groupId>
<artifactId>ssm2</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm2 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.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<mysql.version>8.0.15</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</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-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</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>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>ssm2</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>
domain
Account.java
package com.zjw.domain;
import java.io.Serializable;
/**
* 账户
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
public Account() {
}
public Account(Integer id, String name, Double money) {
this.id = id;
this.name = name;
this.money = 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(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
dao层
package com.zjw.dao;
import com.zjw.domain.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 账户dao接口
*/
@Repository
public interface AccountDao {
//查询所有账户
public List<Account> findAll();
//保存账户信息
public void saveAccount(Account account);
}
mapper
AccountDao.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.zjw.dao.AccountDao">
<!--查询所有-->
<select id="findAll" resultType="com.zjw.domain.Account">
select * from account ;
</select>
<insert id="saveAccount" parameterType="Account">
<selectKey keyProperty="id" keyColumn="id" order="AFTER" resultType="int">
select LAST_INSERT_ID();
</selectKey>
insert into account(name,money) values (#{name},#{money}) ;
</insert>
</mapper>
service层
AccountService.java 接口
package com.zjw.service;
import com.zjw.domain.Account;
import java.util.List;
public interface AccountService {
//查询所有账户
public List<Account> findAll();
//查询账户信息
public void saveAccount(Account account);
}
AccountServiceImpl.java 实现类
package com.zjw.service.impl;
import com.zjw.dao.AccountDao;
import com.zjw.domain.Account;
import com.zjw.service.AccountService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Resource
private AccountDao accountDao ;
@Override
public List<Account> findAll() {
System.out.println("AccountServiceImpl....findAll方法...");
return accountDao.findAll();
}
@Override
public void saveAccount(Account account) {
System.out.println("AccountServiceImpl....saveAccount方法...");
accountDao.saveAccount(account);
System.out.println(account);
// int a = 1/0;
}
}
exception包
SysException.java
package com.zjw.exception;
/**
* 自定义异常类
*/
public class SysException extends Exception {
//存储提示信息
private String message ;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public SysException(String message) {
this.message = message;
}
}
异常处理器
SysExceptionResolver.java
package com.zjw.exception;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 异常处理器
*/
@Component
public class SysExceptionResolver implements HandlerExceptionResolver {
/**
* 处理异常业务逻辑
* @param request
* @param response
* @param handler
* @param ex
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//获取到异常对象
SysException e = null;
if (ex instanceof SysException){
e = (SysException) ex;
}else {
e = new SysException("系统正在维护中");
}
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg",e.getMessage());
mv.setViewName("error/error");
return mv;
}
}
contorller层
package com.zjw.controller;
import com.zjw.domain.Account;
import com.zjw.exception.SysException;
import com.zjw.service.AccountService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 账户Web
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Resource
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(Model model){
System.out.println("AccountController...findAll方法...");
List<Account> list = accountService.findAll();
model.addAttribute("list",list);
return "list";
}
@RequestMapping("/saveAccount")
public void saveAccount(Account account, HttpServletRequest request , HttpServletResponse response) throws Exception {
try {
System.out.println("AccountController...saveAccount...");
accountService.saveAccount(account);
response.sendRedirect(request.getContextPath()+"/account/findAll");
} catch (Exception e) {
e.printStackTrace();
throw new SysException("保存用户出错了。。。");
}
}
}
配置文件
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties" />
<!--Spring整合MyBatis框架-->
<!--配置连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClass}"/>
<property name="jdbcUrl" value="${jdbcUrl}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
<!--配置SqlSessionFactory工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>
<!--扫描domain包,使用别名-->
<property name="typeAliasesPackage" value="com.zjw.domain"/>
<!--扫描sql配置文件:mapper需要的xml文件-->
<property name="mapperLocations" value="classpath:mapper/*/*.xml"/>
</bean>
<!--配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--给出需要扫描Dao接口包-->
<property name="basePackage" value="com.zjw.dao"/>
</bean>
<!--配置Spring框架声明式事务管理-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置AOP增强-->
<aop:config>
<aop:pointcut id="pt1" expression="execution(* com.zjw.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1" />
</aop:config>
<!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理-->
<context:component-scan base-package="com.zjw">
<!--配置哪些注解不扫描:不扫描Controller注解-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
</beans>
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--包扫描
base-package:指定要扫描的包
user-default-filters:不使用默认的过滤器
默认为true,会扫描Controller、Service、Repository、Component注解
-->
<context:component-scan base-package="com.zjw" use-default-filters="false">
<!--只扫描controller注解-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置的视图解析器对象-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--过滤静态资源-->
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/images/**" location="/images/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<!--开启SpringMVC注解的支持-->
<mvc:annotation-driven/>
</beans>
db.properties
driverClass=com.mysql.cj.jdbc.Driver
jdbcUrl=jdbc:mysql://192.168.234.128:3306/ssm?useSSL=false&serverTimeZone=Asia/Shanghai
user=root
password=a@123456
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=d:\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
Web层
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--配置文件的路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--解决中文乱码-->
<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置前端控制器-->
<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:springmvc.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>
</web-app>
index.jsp
<%--
Created by IntelliJ IDEA.
User: zjw
Date: 20/07/01
Time: 19:00
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<a href="/account/findAll">查询所有</a>
<form action="/account/saveAccount" method="post">
姓名:<input type="text" name="name" /><br>
金额:<input type="text" name="money" /><br>
<input type="submit" value="保存">
</form>
</body>
</html>
list.jsp
<%--
Created by IntelliJ IDEA.
User: zjw
Date: 20/07/01
Time: 19:00
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>list</title>
</head>
<body>
list.jsp
<table border="1">
<tr>
<th>id</th>
<th>姓名</th>
<th>金额</th>
</tr>
<c:forEach items="${list}" var="account">
<tr>
<td>${account.id}</td>  
<td>${account.name}</td>
<td>${account.money}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
error.jsp
<%--
Created by IntelliJ IDEA.
User: zjw
Date: 20/06/27
Time: 22:24
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>error</title>
</head>
<body>
${errorMsg}
</body>
</html>
测试(可选)
dao测试
TestAccountDao.java
package com.zjw.dao;
import com.zjw.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.util.List;
/**
* 测试AccountDao层
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestAccountDao {
@Resource(name = "accountDao")
private AccountDao accountDao;
/**
* 测试是否可以查询到数据
*
* 通过
*/
@Test
public void testFindAll(){
List<Account> accountList = accountDao.findAll();
for (Account account : accountList) {
System.out.println(account);
}
}
/**
* 测试保存数据,是否返回id,数据库是否有数据。
*
* 通过,返回了id
*/
@Test
public void testSaveAccount(){
Account account = new Account();
account.setName("张三三");
account.setMoney(99.99);
accountDao.saveAccount(account);
System.out.println(account);
}
}
service
TestAccountService.java
package com.zjw.service;
import com.zjw.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.util.List;
/**
* 测试AccountService
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestAccountService {
@Resource(name = "accountService")
private AccountService accountService;
/**
* 测试是否可以查询到数据
*
* 通过
*/
@Test
public void testFindAll(){
List<Account> accountList = accountService.findAll();
for (Account account : accountList) {
System.out.println(account);
}
}
/**
* 一、测试保存数据,是否返回id,数据库是否有数据。
* 通过,返回了id
*
* 二、测试事务
* 通过
*/
@Test
public void testSaveAccount(){
Account account = new Account();
account.setName("张44");
account.setMoney(99.99);
accountService.saveAccount(account);
System.out.println(account);
}
}
spring
TestMybatis.java
package com.zjw.spring;
import com.zjw.dao.AccountDao;
import com.zjw.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.util.List;
/**
* 测试mybatis层是否连通数据库
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestMybatis {
@Resource(name = "accountDao")
private AccountDao accountDao;
/**
* 测试mybatis是否可以查询到数据
*/
@Test
public void testDao(){
List<Account> accountList = accountDao.findAll();
for (Account account : accountList) {
System.out.println(account);
}
}
}
TestServiceMybatis.java
package com.zjw.spring;
import com.zjw.domain.Account;
import com.zjw.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import java.util.List;
/**
* 测试service层往下
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestServiceMybatis {
@Resource(name = "accountService")
private AccountService accountService;
@Test
public void testServiceMybatis(){
//可以查出数据,Service层没有问题
List<Account> accountList = accountService.findAll();
for (Account account : accountList) {
System.out.println(account);
}
}
}
TestSpringBean.java
package com.zjw.spring;
import com.zjw.dao.AccountDao;
import com.zjw.service.AccountService;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
/**
* 测试Sping中的Bean是否加载到容器
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestSpringBean {
@Resource(name = "accountService")
private AccountService accountService;
@Resource(name = "accountDao")
private AccountDao accountDao;
@Test
public void testService(){
//打印地址,代表Service被加载到容器中
System.out.println(accountService);
}
@Test
public void testDao(){
//打印地址,代表Dao被加载到容器中
System.out.println(accountDao);
}
}
---------------
我每一次回头,都感觉自己不够努力,所以我不再回头。
---------------