一.SpringBoot的综合案例
1.新建工程
1.1配置Maven
1.2配置pom文件,以下为部分代码
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.4.5</version>
</parent>
<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>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--导入对应功能的starter-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-starter-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
<!--注意版本-->
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
</dependencies>
2.在java目录下新建包为com/hhh
2.1hhh包下新建包config,其包下新建类MyConfig,为访问静态资源做配置
package com.hhh.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/html/**").addResourceLocations("classpath:/html/");
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");
/*前面是访问路径,后面是存放路径*/
}
}
2.2hhh包下新建包controller,其包下新建类ManagerController
package com.hhh.controller;
import com.hhh.domain.Manager;
import com.hhh.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
//Manager相关的请求处理
@Controller
@RequestMapping("/hello")
public class ManagerController {
@Autowired
private ManagerService managerService;
/*第一个方法*/
@RequestMapping(value = "/findAll", method = RequestMethod.GET)
@ResponseBody
public List<Manager> findAll() {
List<Manager> all = managerService.findAll();
return all;
}
/*第二个方法*/
@PostMapping(value = "/insert")
@ResponseBody
public String insert(@RequestBody Manager manager){
managerService.insert(manager);
return "success";
}
/*第三个方法*/
@GetMapping(value = "/delete")
@ResponseBody
public String delete(String id){
managerService.delete(id);
return "success";
}
}
2.3hhh包下新建包dao,其包下新建接口ManagerDao
package com.hhh.dao;
import com.hhh.domain.Manager;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
//数据库层
@Mapper
public interface ManagerDao {
public List<Manager> findAll();
public void insert(Manager manager);
public void delete(String id);
}
2.4hhh包下新建包domain,其包下新建类Manager
package com.hhh.domain;
public class Manager {
String id;
String name;
public Manager(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Manager{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
'}';
}
}
2.5hhh包下新建包service,其包下新建类ManagerService
package com.hhh.service;
import com.hhh.domain.Manager;
import java.util.List;
public interface ManagerService {
public List<Manager> findAll();
public void insert(Manager manager);
public void delete(String id);
}
而后其包下新建包impl,其包下新建类ManagerServiceImpl
package com.hhh.service.impl;
import com.hhh.dao.ManagerDao;
import com.hhh.domain.Manager;
import com.hhh.service.ManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ManagerServiceImpl implements ManagerService {
//service层持有dao层的对象
@Autowired
private ManagerDao managerDao;
@Override
public List<Manager> findAll() {
//这里可能会组合多dao层方法的逻辑来达到复杂的效果
List<Manager> all=managerDao.findAll();
return all;
}
@Override
public void insert(Manager manager) {
//调用dao层插入方法
managerDao.insert(manager);
}
@Override
public void delete(String id) {
//调用dao层删除方法
managerDao.delete(id);
}
}
2.7在com/hhh包下新建启动类
package com.hhh;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
//启动类
@SpringBootApplication
public class AppApplication {
public static void main(String[] args) {
SpringApplication.run(AppApplication.class,args);
}
}
3.在resources目录下新建包为com/hhh/mapper,其包下新建sql文件
<?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.hhh.dao.ManagerDao">
<select id="findAll" resultType="com.hhh.domain.Manager">
SELECT * FROM manager1
</select>
<!--这里的manager1为ssmframe数据库中的其中一个表-->
</mapper>
4.在resources目录下新建包为html,其包下新建静态资源Test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<h1>静态资源访问测试</h1>
</body>
</html>
5.在resources目录下配置文件application.properties,在里面配置数据库连接的信息
#端口设置
server.port=8081
#数据库连接设置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssmframe
spring.datasource.username=root
spring.datasource.password=hyt123456
#别名设置和到sql文件扫描路径的配置
mybatis.type-aliases-package=com.hhh.domain
mybatis.mapper-locations=classpath:com/hhh/mapper/*.xml
6. 启动启动类,访问静态资源查看效果
二.SpringBoot整合swagger
1.swagger
一个可以自动根据代码生成接口文档的框架,可以方便接口的调试
2.引入swagger依赖
<!-- 引入swagger依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
3.刷新工程
4.在config包下创建类SwaggerConfig
package com.hhh.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
@Configuration
public class SwaggerConfig {
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("test")
.description("接口测试")
.build();
}
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
5.启动工程,在浏览器中访问如下地址:http://localhost:8081/swagger-ui.html,出现如下画面![](https://i-blog.csdnimg.cn/blog_migrate/345ecc867f1c5fde07c8388b550a97c7.png)
可以点击测试接口
三.springboot配置过滤器和拦截器(失败)
1.在hhh包下创建包名为filter,其下新建类FirstFilter(javax.servlet),实现Filter接口并实现抽象方法(Alt+Enter)
package com.hhh.filter;
import javax.servlet.*;
import java.io.IOException;
@Component("firstFilter")
public class FirstFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("filter 执行了");
/*放行这个请求*/
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
2.在配置类中去配置(或者在启动类中配置),这里在MyConfig类中去使用filter(代码报错)
package com.hhh.config;
import org.mapstruct.Qualifier;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.Filter;
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/html/**").addResourceLocations("classpath:/html/");
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/js/");
/*前面是访问路径,后面是存放路径*/
/*
@Bean
//注册Filter
public FilterRegistrationBean filterRegistrationBean(@Qualifier("firstFilter") Filter filter){
FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
filterRegistrationBean.setFilter(filter);
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.setOrder(1);
return filterRegistrationBean;
}
*/
}
}
3.在hhh包下创建包名为intecerptor,其下新建类firstIneceptor
package com.hhh.intecerptor;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class firstIneceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器执行了");
return true;
}
}
4.在配置类中去配置,这里只能MyConfig类中去使用f拦截器,该类实现了MVC,代码报错
/* //注册拦截器,只能放在实现Mvc的类里执行
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration interceptorRegistration = registry.addInterceptor(new FirstInteceptor());
interceptorRegistration.order(1);
interceptorRegistration.addPathPatterns("/**");
}*/
5.启动工程,访问浏览器,查看效果
四.springboot中的事务控制(失败)
1.新建一个工程SpringBoot_Control
1.1在pom文件中添加父工程
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.4.5</version>
</parent>
1.2在pom文件中添加相应依赖
<!--导入大对应功能的starter-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mybatis-starter-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
1.3刷新依赖
2.数据库的事务
指的是能更新数据库中各种数据项的一个执行单位(unit),要么同时成功,要不同时失败。一个事务可以是一条SQL语句或者一组SQL语句。
3.事务的四个属性
原子性、一致性、隔离性、持久性
4.数据库环境准备
在ssmframe数据库中创建表t_account,账号表,插入数据
#使用数据库
use ssmframe;
#创建数据表
create table t_account(
numben varchar(30) primary key,
name varchar(30),
balance int
);
#插入数据
insert into t_account values('1','张安的账户',500);
insert into t_account values('2','李思的账户',500);
5.springboot中的事务控制
springboot不需要进行特别的设置,按照正常的配置整合spring和mybatis后,在需要进行事务控制的类或方法上加上@Transaction注解,即可对其进行事务控制,可通过rollbackFor属性来控制发生那种类型的异常需要回滚事务
6.在前面工程的基础上进行测试
6.1在domain包下创建类为Account,里面的属性和数据表t_account中的字段一一对应
package com.hhh.domain;
public class Account {
private String number;
private String name;
private int balance;
//无参构造方法
public Account(){
}
public Account(String number, String name, int balance) {
this.number = number;
this.name = name;
this.balance = balance;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
@Override
public String toString() {
return "Account{" +
"number='" + number + '\'' +
", name='" + name + '\'' +
", balance=" + balance +
'}';
}
}
6.2这里写一下service层,在service包下创建接口AccountService
package com.hhh.service;
public interface AccountService {
//定义一个转账的方法
String transfer();
}
6.3而后提供一个实现类,在service包下创建包Impl(已有不用创建),包下创建类为AccountServiceImpl,实现接口
package com.hhh.service.impl;
import com.hhh.service.AccountService;
public class AccountServiceImpl implements AccountService {
@Override
public String transfer() {
return null;
}
}
6.4涉及数据库操作,在dao层新建接口AccountDao
package com.hhh.dao;
import com.hhh.domain.Account;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AccountDao {
//查询
Account findByNumber(String number);
//更新账号金额
void update(Account account);
}
6.5在resource的包com/hhh/mapper 包下新建sql语句配置文件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.hhh.dao.AccountDao">
<!--写查询语句-->
<select id="findByNumber" parameterType="string" resultType="account">
select * from t_account where number=#{number}
</select>
<!--写更新语句-->
<!-- parameterMap="account"这里的值为Account实体类的全路径-->
<!--但是在application.properties文件中配置了别名,这里account为实体类的别名-->
<update id="update" parameterMap="account">
update t_account set
balance=#{balance} where
number=#{number}
</update>
</mapper>
6.6具体写AccountServiceImpl类中代码
package com.hhh.service.impl;
import com.hhh.dao.AccountDao;
import com.hhh.domain.Account;
import com.hhh.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AccountServiceImpl implements AccountService {
//注入AccountDao
@Autowired
private AccountDao accountDao;
@Override
@Transactional //事务控制
public String transfer() {
//1.给张安减钱
//查张安
Account za = accountDao.findByNumber("1");
//得到金额减去钱数
za.setBalance(za.getBalance()-100);
//更新数据
accountDao.update(za);
//2.给李思加钱
Account ls = accountDao.findByNumber("2");
ls.setBalance(ls.getBalance()+100);
accountDao.update(ls);
return "success";
}
}
6.7在contoller层创建AccountController
package com.hhh.controller;
import com.hhh.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/account")
public class AccountController {
//在controller层调用service层方法,注入AccountService,加上@Autowired注解
@Autowired
private AccountService accountService;
@RequestMapping("/transfer")
public String transfer(){
return accountService.transfer();
}
}
6.8在resource目录下创建配置文件application.properties
#设置端口号
server.port=8082
#数据库设置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssmframe
spring.datasource.username=root
spring.datasource.password=hyt123456
#设置别名和sql文件的扫描路径
mybatis.type-aliases-package=com.hhh.domain
mybatis.mapper-locations=classpath:com/hhh/mapper/*.xml
6.9启动工程,访问浏览器,查看效果