ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

springboot学习

2022-09-03 10:34:46  阅读:144  来源: 互联网

标签:springboot 配置文件 spring 配置 boot 学习 user public


springboot学习

官方文档:https://spring.io/projects/spring-boot

1、简介

1.1、什么是spirngboot?

springboot在spring的基础之上,搭建起来的框架,能够帮助我们整合市面上最流行的框架,帮助我们快速搭建起来项目。

springboot不是新的技术,而是新的框架,是基于spring来搭建起来的。

特性:约定大于配置!

1.2、为什么使用springboot

  • 开发效率快,内置有配置好的版本依赖。
  • 基于spring。
  • 轻松上手

2、第一个 SpringBoot 项目

我的开发环境:

  • java 8
  • Maven-3.6.1
  • SpringBoot 2.6.11

2.6.11官方文档:https://docs.spring.io/spring-boot/docs/2.6.11/reference/htmlsingle/

创建springboot有两种方式:

  1. 在https://start.spring.io/上创建后,下载完成,通过IDEA打开即可。
  2. 在IDEA中直接创建。

2.1、创建项目

1、页面创建

2、IDEA创建

两种创建方式大致相同。

2.2、启动项目并访问

1、创建一个HelloController.java

@RestController
public class HelloController {

    @GetMapping("/")
    public String hello(){
        return "Hello springboot";
    }
}

2、启动项目

访问:http://localhost:8080/

这样一个web应用就创建完成,是不是很快。

3、Spring Boot启动器

我们在创建项目的时候添加了一个web的依赖。

通过pom.xml查看。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

会发现,只添加spring-boot-starter-web就可以进行web开发了。并且不用声明版本号。

启动器包含许多依赖项,包括版本号,可以添加这些依赖项使项目快速启动并运行。

官方启动器命名规则:spring-boot-starter-*,其中*是特定类型的应用程序。例如,spring-boot-starter-web

第三方启动器命名规则:以项目名称开头*-boot-starter。例如,MyBatis-Plus。他的命名是mybatis-plus-boot-starter

Spring Boot 应用程序启动器

官方文档:https://docs.spring.io/spring-boot/docs/2.6.11/reference/htmlsingle/#using.build-systems.starters

整合第三方技术的两种方式

  • 自定义
  • 找starter

4、配置文件

springboot支持两种格式的配置文件,.properties.yml

如果在同一位置有同时具有.properties和.yml格式的配置文件,.properties优先。

如果存在多个相同配置,会有优先级。

4.1、配置文件区别

.properties.yml区别在于语法结构不同。

  • .properties结构 :key=value
server.port=8081
  • .yml结构 :key: value
server:
  port: 8081

4.2、实体类获取配置信息

加载单个配置

// @Value 加载单个配置
@Value("${student.name}")

加载多个配置

案例:创建学生对象,用于默认就把配置信息加载进去。

1、在springboot项目中的resources目录下新建一个文件 application.yml

student:
  name: Zhang San
  birthdate: 1990/09/01
  interests: [eat, sleep]

2、添加实体类

//注册bean到容器中
@Component
// 开头为student配置
@ConfigurationProperties(prefix = "student")
@Data
public class Student {
    private String name;
    private Date birthdate;
    private List<String> interests;
}

idea提示没有找到springboot配置注解处理器。

需要添加springboot配置注解处理器,方便在Test测试。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

3、测试类中测试。

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    Student student;

    @Test
    void contextLoads() {
        System.out.println(student);
    }

}

结果:

4.3、加载指定的配置文件

日常开发中,配置文件可能存在多个。

1、我们去在resources目录下新建一个student.properties文件,yaml不生效。

student.name=Wang mou
student.birthdate=1995/09/01
student.interests=[sleep,dream]

2、修改配置类

//注册bean到容器中
@Component
// 开头为student配置
@ConfigurationProperties(prefix = "student")
// 资源路径
@PropertySource(value = "classpath:student.properties")
@Data
public class Student {
    private String name;
    private Date birthdate;
    private List<String> interests;
}

3、测试查看效果

4.4、yaml语法总结

  • 语法要求严格

  • 空格不能省略

  • 以缩进来控制层级关系

  • 对大小写敏感

# 普通格式:
k: v
# 对象格式:
k:
  v1:
  v2:
# 数组模式:
k:
  - v
  - v
  - v
  
# 行内写法
k: {k1:v1,k2:v2}
k: {v,v,v}

4.5、配置文件优化级

springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件:

1.类路径
  1.类路径
  2.类路径/config包
2.当前目录
  1.当前目录
  2.当前目录中的/config子目录
  3.子目录的/config直接子目录

4.6、多环境切换

profile是Spring对不同环境提供不同配置功能的支持,可以通过激活不同的环境版本,实现快速切换环境;

我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml , 用来指定多个环境版本;

例如:

application-test.yml:代表测试环境配置

application-dev.yml:代表开发环境配置

但是Springboot并不会直接启动这些配置文件,它默认使用application.properties主配置文件,如果没有就会找application.yml

我们需要通过一个配置来选择需要激活的环境:

spring:
  profiles:
    active: dev #使用开发环境。

5、自动配置原理

SpringBoot官方文档中有大量的配置。我们无法全部记住。

我们来简单分析一下。

5.1、分析自动配置原理

这块内容,建议大家去看视频。

我们以HttpEncodingAutoConfiguration(Http编码自动配置)为例。

解释自动配置原理;

@Configuration //表示这是一个配置类,和以前编写的配置文件一样,也可以给容器中添加组件;

//启动指定类的ConfigurationProperties功能;
  //进入这个HttpProperties查看,将配置文件中对应的值和HttpProperties绑定起来;
  //并把HttpProperties加入到ioc容器中
@EnableConfigurationProperties({HttpProperties.class}) 

//Spring底层@Conditional注解
  //根据不同的条件判断,如果满足指定的条件,整个配置类里面的配置就会生效;
  //这里的意思就是判断当前应用是否是web应用,如果是,当前配置类生效
@ConditionalOnWebApplication(type = Type.SERVLET)

//判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器;
@ConditionalOnClass({CharacterEncodingFilter.class})

//判断配置文件中是否存在某个配置:spring.http.encoding.enabled;
  //如果不存在,判断也是成立的
  //即使我们配置文件中不配置spring.http.encoding.enabled=true,也是默认生效的;
@ConditionalOnProperty(
    prefix = "spring.http.encoding",
    value = {"enabled"},
    matchIfMissing = true
)

public class HttpEncodingAutoConfiguration {
    //他已经和SpringBoot的配置文件映射了
    private final Encoding properties;
    //只有一个有参构造器的情况下,参数的值就会从容器中拿
    public HttpEncodingAutoConfiguration(HttpProperties properties) {
        this.properties = properties.getEncoding();
    }
    
    //给容器中添加一个组件,这个组件的某些值需要从properties中获取
    @Bean
    @ConditionalOnMissingBean //判断容器没有这个组件?
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE));
        return filter;
    }
    //。。。。。。。
}

一句话总结 :根据当前不同的条件判断,决定这个配置类是否生效!

如果没有把对应的依赖引用进来,这个配置类也会不生效。

通过不同的条件来进行判断是否要启动配置。

  • 一但这个配置类生效;这个配置类就会给容器中添加各种组件;

  • 这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的;

  • 这样就可以形成我们的配置文件可以动态的修改springboot的内容。

  • 所有在配置文件中能配置的属性都是在xxxxProperties类中封装着;

  • 配置文件能配置什么就可以参照某个功能对应的这个属性类

5.2、总结

1、SpringBoot启动时会加载大量的自动配置类

2、我们看我们需要的功能有没有在SpringBoot默认写好的自动配置类当中

3、我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件存在其中,我们就不需要再去手动配置了,如果不存在我们再手动配置)

4、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性,我们只需要在配置文件中指定这些属性即可;

XXXXAutoConfiguration:自动配置类:给容器添加组件,这些组件要赋值就需要绑定一个XXXXProperties类

XXXXProperties:里面封装配置文件中相关属性;

6、Web开发

6.1、静态资源管理

6.1.1、静态资源访问

1、默认情况下,Spring Boot 从类路径中的/static (或/public/resources/META-INF/resources)目录或 ServletContext的根目录提供静态内容。

访问 : 当前项目根路径/ + 静态资源名

原理: 静态映射/**。

请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面

添加图片到resource下的static里。

访问 : 当前项目根路径/ + 静态资源名

原理: 静态映射/**。

请求进来,先去找Controller看能不能处理。不能处理的所有请求又都交给静态资源处理器。静态资源也找不到则响应404页面

6.1.2、静态资源前缀

可以添加访问静态资源前缘。

spring:
  mvc:
    static-path-pattern: /res/**

现在访问就是: 当前项目根路径 + /res + 静态资源名

6.1.3、webjar

webjar官网:https://www.webjars.org/

WebJars是可以让大家以jar包的形式来使用前端的各种框架、组件。

例如,引用jquery。

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.6.1</version>
</dependency>

访问路径:当前项目根路径/ + webjars/**。

http://localhost:8081/webjars/jquery/3.6.1/jquery.js

6.1.4、首页支持

  • 静态资源路径下 index.html
  • 可以配置静态资源路径。
  • 不能与静态资源前缀共用。
spring:
  resources:
    static-locations: [classpath:/haha/]

6.2、请求参数处理

6.2.1、Rest风格

RESTFUL是一种网络应用程序的设计风格和开发方式。

对比:

功能 传统请求 Rest风格
获取用户 /user/getUser (GET请求) /user (GET请求)
保存用户 /user/saveUse (POST请求) /user (POST请求)
修改用户 /user/editUser (POST请求) /user (PUT请求)
删除用户 /user/deleteUser(POST请求) /user (DELETE请求)

springboot用法:表单method=post,隐藏域 _method=put

1、开启页面表单的Rest功能

spring:
  mvc:
    hiddenmethod:
      filter:
        # 开启页面表单的Rest功能
        enabled: true

2、添加页面请求

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script src="/webjars/jquery/3.6.1/jquery.js"></script>
<body>
    <h1>首页</h1>
    <button id="getUser">获取用户</button>
    <button id="saveUser">保存用户</button>
    <button id="editUser">修改用户</button>
    <button id="deleteUser">删除用户</button>
    <p id="msg"></p>
<script>
    $("#getUser").on("click",()=>{
        $.get("/user",(res)=>{
            $("#msg").text(res);
        })
    });
    $("#saveUser").on("click",()=>{
        sendAjax(null);
    });
    $("#editUser").on("click",()=>{
        sendAjax('PUT');
    });
    $("#deleteUser").on("click",()=>{
        sendAjax("DELETE");
    });

    function sendAjax(type){
        let data = {'_method':type}
        $.post("/user",data,(res)=>{
            $("#msg").text(res);
        })
    }
</script>
</body>
</html>

3、添加后端接口

// 组合注解,@Controller + RequestBody
@RestController
@RequestMapping("/user")
public class UserController {

    // 普通写法
    // @RequestMapping(value = "/user",method = RequestMethod.GET)
    // 精简写法
    @GetMapping
    public String getUser(){
        return "get user";
    }
    @PostMapping
    public String saveUser(){
        return "post user";
    }
    @PutMapping
    public String editUser(){
        return "put user";
    }
    @DeleteMapping
    public String deleteUser(){
        return "delete user";
    }
}

为什么明明请求方式是POST,会跑到别的接口。

  • 核心Filter;HiddenHttpMethodFilter。
  • 由过滤器来判断改变。

如果请求方式是直接发送Put、delete等方式请求,无需Filter。

扩展:_method 的值可以自定义,只需要重新实现过滤器方法即可。

//自定义filter
@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
    HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
    methodFilter.setMethodParam("_m");
    return methodFilter;
}

6.2.2、参数注释

  • @PathVariable、从请求路径上获取参数
  • @RequestHeader、从请求头上获取参数
  • @RequestParam、从请求参数上获取参数
  • @CookieValue、从请求Cookie中获取参数
  • @RequestBody、从请求body上获取参数
  • @MatrixVariable、从请求路径上;分割获取变量
    • SpringBoot默认禁用
    • 语法: 请求路径/test;user=jack;age=16,interests=sleep,dream
    • 后端接收,@MatrixVariable("user") String name,@MatrixVariable("age") Integer age,@MatrixVariable("interests") List<String> interests


@GetMapping("/{id}")
public String getParam(@PathVariable("id") Integer id,
                      @RequestHeader("Host") String host,
                      @RequestParam("name") Integer name,
                      @CookieValue("_username") String usernmae){
    
}

@PostMapping
public void postMethod(@RequestBody String content){
}

// 可以传多个值,用对象来接收,存在相同属性时,会自动封装到里面。
@PostMapping
public void postMethod(@RequestBody Student student){
}

6.3、数据响应

数据响应,一般分两个类型:

  • 响应页面
  • 响应数据

响应数据的格式可以是json,xml,io流等。

SpringMVC支持返回值

ModelAndView
Model
View
ResponseEntity 
ResponseBodyEmitter
StreamingResponseBody
HttpEntity
HttpHeaders
Callable
DeferredResult
ListenableFuture
CompletionStage
WebAsyncTask
有 @ModelAttribute 且为对象类型的
@ResponseBody 注解

6.4、模板引擎

SpringBoot默认不支持 JSP,需要引入第三方模板引擎技术实现页面渲染。

6.4.1Thymeleaf模板引擎

官网:https://www.thymeleaf.org/

前端显示页面,是html页面。我们以前开发,做的是jsp页面,jsp可以动态渲染一些数据在页面上,可以写Java代码。JSP+Servlet+JavaBean,是我们很早之前就不用了,企业也用得少。

现在SpringBoot推荐Thymeleaf模板引擎。

6.4.2、基本语法

表达式名字 语法 用途
变量取值 ${...} 获取请求域、session域、对象等值
选择变量 *{...} 获取上下文对象值
消息 #{...} 获取国际化等值
链接 @{...} 生成链接
片段表达式 ~{...} jsp:include 作用,引入公共页面片段
<!-- 常用标签,一般都是  th:XXX -->
<!-- 需要设置头部(非标准HTML5 规范),也可以不设置 -->
<html xmlns:th="http://www.thymeleaf.org">
    
<!-- 不设置头部的写法(符合HTML5规范) -->
<p data-th-text="${msg}">msg</p>
    
<!--设置文本-->
<p th:text="${msg}">提醒消息</p>

<!--设置文本-->
<a th:href="@{href}">超链接</a>

<!-- 设置属性值 -->
<input type="text" th:id="${student.id}" />
    
    
<!-- 获取session -->
<p th:id="${#session.user}" />

6.4.3、thymeleaf使用

1、添加thymeleaf依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、创建文件,springboot帮我们配置好了。我们直接开发页面即可。

// 接口
@Controller
public class IndexController {

    @GetMapping("/thymeleaf")
    public String index(Model model) {
        model.addAttribute("msg","hello thymeleaf");
        model.addAttribute("link","www.baidu.com");
        // 返回视图层
        return "thymeleaf";
    }
}

templates下新建thymeleaf.html;

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1 data-th-text="${msg}">提醒消息</h1>
    <h2>
        <a data-th-href="${link}">超连接</a>
    </h2>
</body>
</html>

3、效果

6.5、登录功能 + 拦截器

例子:访问项目,需要登录,如果没有登录就不能访问。

1、添加登录页面。login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LOGIN</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html {
            height: 100%;
        }
        body {
            height: 100%;
        }
        .container {
            height: 100%;
            background-image: linear-gradient(to right, #fbc2eb, #a6c1ee);
        }
        .login-wrapper {
            background-color: #fff;
            width: 358px;
            height: 588px;
            border-radius: 15px;
            padding: 0 50px;
            position: relative;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }
        .header {
            font-size: 38px;
            font-weight: bold;
            text-align: center;
            line-height: 200px;
        }
        .input-item {
            display: block;
            width: 100%;
            margin-bottom: 20px;
            border: 0;
            padding: 10px;
            border-bottom: 1px solid rgb(128, 125, 125);
            font-size: 15px;
            outline: none;
        }
        .input-item:placeholder {
            text-transform: uppercase;
        }
        .btn {
            border: 0;
            font-size: 20px;
            text-align: center;
            padding: 10px;
            width: 100%;
            margin-top: 40px;
            background-image: linear-gradient(to right, #a6c1ee, #fbc2eb);
            color: #fff;
        }
        .msg {
            color:red;
            text-align: center;
            line-height: 88px;
        }
        a {
            text-decoration-line: none;
            color: #abc1ee;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="login-wrapper">
        <div class="header">Login</div>
        <div class="form-wrapper">
            <form data-th-action="@{/login}" method="post">
                <input type="text" name="username" placeholder="username" class="input-item" /  >
                <input type="password" name="password" placeholder="password" class="input-item" />
                <input type="submit" class="btn" value="Login" />
            </form>
        </div>
        <div class="msg" data-th-text="${msg}">
            Don't have account?
            <a href="#">Sign up</a>
        </div>
    </div>
</div>
</body>
</html>

2、添加登录接口。

@Controller
public class LoginController {
    @GetMapping("/")
    public String index() {
        // 返回视图层
        return "/login/login";
    }
    
    @PostMapping("/login")
    public String login(String username, String password, HttpSession session, Model model) {
        if(StringUtils.hasLength(username) && "123456".equals(password)){
            //把登陆成功的用户保存起来
            session.setAttribute("loginUserName",username);
            //登录成功重定向到 thymeleaf ;  重定向防止表单重复提交
            return "redirect:/thymeleaf";
        }else {
            model.addAttribute("msg","账号密码错误");
            //回到登录页面
            return "/";
        }
    }
}

3、添加拦截器。

继承HandlerInterceptor 接口。

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 目标方法执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 请求路径 request.getRequestURI();
        //登录检查逻辑
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUserName");
        if(loginUser != null){
            //放行
            return true;
        }
        //拦截住。未登录。跳转到登录页
        request.setAttribute("msg","请先登录");
        
        // 跳转
        request.getRequestDispatcher("/").forward(request,response);
        return false;
    }

}

4、配置拦截器

@Configuration
public class AdminWebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                // 所有请求都被拦截包括静态资源
                .addPathPatterns("/**")
                // 放行的请求
                .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**");
    }
}

测试:

6.6、异常处理

错误处理

  • 默认情况下,Spring Boot提供/error处理所有错误的映射
  • 对于浏览器客户端,响应一个“ whitelabel”错误视图,以HTML格式呈现相同的数据
  • 对于机器客户端,它将生成JSON响应,其中包含错误,HTTP状态和异常消息的详细信息。

SpringBoot也为我们提供了自定义错误页的功能。

自定义错误页的话可以在静态路径(如 /static/ )下的error目录。或放在模板目录(如 /templates/ )下的error目录,都会被SpringBootz自动解析。

DefaultErrorAttributes:定义错误页面中可以包含哪些数据。

7、数据库连接

按照我们学习这么久,要连接数据肯定需要添加依赖才可以连接。

7.1、添加JDBC依赖

1、添加jdbc依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

发现同时依赖数据池(速度快)

2、添加数据库驱动。

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

默认配置的mysql驱动版本8.0.30

可以进行修改。

<!-- 方法一,直接在下面写版本 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.49</version>
</dependency>

<!-- 方法一,2、重新声明版本(maven的属性的就近优先原则)-->
<properties>
    <mysql.version>5.1.49</mysql.version>
</properties>

7.2、修改配置项

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/sp_boot_demo
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

7.3、测试

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Test
    void contextLoads() {
        String sql = "select count(*) from sys_user";
        Long totle = jdbcTemplate.queryForObject(sql, Long.class);
        System.out.println(totle);
    }

}

8、使用Druid数据源

druid官方github地址: https://github.com/alibaba/druid

Druid相对于其他数据库连接池有着强大的监控特性,通过监控特性可以清楚知道连接池和SQl的工作情况。

8.1、添加依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.17</version>
</dependency>

8.2、添加配置

SpringBoot配置示例 :https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

配置项列表: https://github.com/alibaba/druid/wiki/DruidDataSource配置属性列表

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/sp_boot_demo
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

    druid:
      aop-patterns: com.atguigu.admin.*  #监控SpringBean
      filters: stat,wall     # 底层开启功能,stat(sql监控),wall(防火墙)

      stat-view-servlet:   # 配置监控页功能
        enabled: true
        login-username: admin
        login-password: admin
        resetEnable: false

      web-stat-filter:  # 监控web
        enabled: true
        urlPattern: /*
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'


      filter:
        stat:    # 对上面filters里面的stat的详细配置
          slow-sql-millis: 1000
          logSlowSql: true
          enabled: true
        wall:
          enabled: true
          config:
            drop-table-allow: false

8.3、测试

访问:http://localhost:8081/druid/login.html

9、整合MyBatis操作

github地址:https://github.com/mybatis/spring-boot-starter

SpringBoot配置文档:https://github.com/mybatis/spring-boot-starter/blob/master/mybatis-spring-boot-autoconfigure/src/site/zh/markdown/index.md

9.1、添加依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.1</version>
</dependency>

9.2、添加配置

# 配置mybatis规则
mybatis:
  #sql映射文件位置
  mapper-locations: classpath:/mappers/*.xml

9.3、测试

1、添加mapper接口

@Mapper
public interface UserMapper {
    public List<SysUser> userList();
}

2、添加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.example.demo.mapper.UserMapper">

    <select id="userList" resultType="com.example.demo.entity.SysUser">
        SELECT * FROM `sys_user`
    </select>
</mapper>

3、测试

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    UserMapper userMapper;

    @Test
    void contextLoads() {
        List<SysUser> sysUsers = userMapper.userList();
        System.out.println(sysUsers);
    }

}

结果:

9.4、注解模式

@Mapper
public interface UserMapper {
    
    public List<SysUser> userList();
    
    // 采用注释
    @Select("SELECT * FROM `sys_user` where id=#{id}")
    public SysUser getById(Long id);
}

测试结果:

SysUser user = userMapper.getById(1L);
System.out.println(user);

推荐:

  • 简单方法直接注解方式
  • 复杂方法编写mapper.xml进行绑定映射

10、总结

  • springboot使用起来方便,能快速搭建spirng环境。
  • spirngboot官网帮我们配置了大部分参数。直接使用即可。
  • 用JavaBean替代xml配置。配置更少了。看起来也简洁了不少。
  • springboot 集成大量的框架,开箱即用。
  • 添加很多新的组合注释。

参考文章:

https://www.yuque.com/atguigu/springboot/rmxq85

https://docs.spring.io/spring-boot/docs/2.6.11/reference/html/

标签:springboot,配置文件,spring,配置,boot,学习,user,public
来源: https://www.cnblogs.com/galenblog/p/16652047.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有