Spring Boot项目的一些配置

Spring Boot
SpringBoot 是由Pivotal团队提供的全新框架,SpringBoot是基于Spring 5.0 开发的项目的起点。
SpringBoot 的设计目的是为了让你尽快的跑起来Spring应用程序,尽可能减少配置文件,
设计目的:用来简化Spring应用程序的初始化构建以及开发过程
从根本上来讲Spring Boot 它默认配置了很多框架的使用方式,就像Maven整合了所有jar包一样
Spring Boot 整合了 整合了大部分的框架 总结:
1.为所有Spring 开发提供了一个更快 更广泛的入门体验
2.接近零配置,无冗余的代码生成和xml强制配置,遵循 约定大于配置
3.集成了大量的常用的第三方的库的配置,SpringBoot应用为这些第三方库提供了几乎可以零配置的开箱即用能力
4.提供了一系列大型项目的常用的非功能特征,如嵌入式服务器,安全性,运行状态检查,外部化配置等
5.Spring Boot不是Spring的替代者。Spring框架通过IOC机制来管理Bean的,SpringBoot依赖Spring框架来管理对象依赖,Spring Boot不是Spring的精简版,而是为了使用Spring做更好的产品。
Thymeleaf模板
Thymeleaf:是一个模板引擎,它可以完全替代JSP,相比较其他的模板引擎,他有如下三点吸引人:
1.Thymeleaf在有网络和无网络的环境下皆可运行,可以让美工在浏览器查看页面的静态效果,这是由于它是支持HTML原型,然后HTML标签中增加额外属性来达到模板+数据的展示方式,浏览器解析HTML时会忽略未定义的标签属性,所以
Thymeleaf的模板可以静态的运行,当有数据返回时,Thymeleaf标签会动态的替换的静态的内容,使页面动态展示。
2.开箱即用,它提供标准和Spring标准两种方言,可以直接套用模板实现JSTL和OGNL表达式效果,避免每天套模板和
改标签,开发人员也可以扩展和创建自定义方言。
3.Thymeleaf提供了Spring标准方言和一个与Spring MVC完美集成的可选模块,可以快速的实现表单的绑定、属性的
编辑器,国际化等功能。
使用JSP的弊端
1.项目目录繁琐
2.页面不洁
3.JSP内置的错误页面不能覆盖Spring Boot的默认错误页面
4.只能打成war包,不能打成jar
5.内置的jetty服务器不支持JSP
使用Thymeleaf:
第一步导入依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
#第二步在application.yml配置:
spring:
  thymeleaf:
    servlet:
      content-type: text/html   #指定内容文本/html
    cache: false   #是否缓存
    encoding: UTF-8   #字符编码
    mode: LEGACYHTML5   #非严格HTML5模式
    prefix: classpath:/templates/   #前缀
    suffix: .html    #后缀
    check-template-location: true   #检查当前的路径是否存在
表达式支持的语法:
	字面(Literals)
	文本字面'one text .....'
	数字文本 '0,35,3.0.....'
	布尔文本'true false'
	空(NULL) null
	文字标记  'one,sometext......'
文本操作:
	字符串连接 +
	文本替换 |文本 ${name}|
算数运算符:
	二元运算符 + - * / %
	单目运算符 - 减号
布尔操作: 
	二元运算符: and or
	布尔否定 一元运算符 ! not
比较和等价
	比较 > < >= <=(gt lt ge le)
	等值运算符 == != (eq ne)
条件运算符
	if- then
	if then-else
	Default
常用标签
关键字
th:id  替换id  <input th:id="'xxxx'+${user.id}"/>
th:text 文本替换 <p th:text="${user.userName}">原有值</p>
th:utext 支持html的文本替换 <p th:utext="${htmlcontent}">原有值</p>
th:object 替换对象  <p th:object="${session.user}"></p>
th:value 属性赋值 	<input th:value="${user.userName}"/>
th:with 变量赋值运算  <p th:with="isEven=${cont}%2==0"></p>
th:style 设置样式  <p th:style="display:...."></p>
th:onclick
th:each  属性赋值  <p th:each="user:${userList}"></p>
th:if   判断条件
th:unless  和th:if判断相反	<p th:unless="${session.user!=null}">Login</p>
th:switch th:case
th:fragment 布局标签,定义一段代码片段,方便其他地方引用
th:include 布局标签 替换内容到引入位置
th:replace 布局标签替换整个标签到引入位置
th:selected	 选择框 选中
th:inline 定义js脚本可以使用变量
th:action 表单的提交地址
th:remove 删除某个属性
th:attr 设置标签的属性,多个属性可以使用逗号隔开
内嵌变量:
dates : java.util.Date 的功能类
numbers : 格式化数字
spring 字符串对象的功能类
objects 对object的功能类
booleas :布尔值 功能方法
arrays : 对数组功能类方法
lists : 对lists功能类方法
maps
sets
...

redis在application.yml配置
spring:
  redis:
    database: 0 #redis的数据库索引,默认为0
    host: localhost
    port: 6379
    #password:
    jedis:
      pool:
        max-active: 100
        max-wait: 3000
        max-idle: 100
    timeout: 1000
配置RedisConfig
package com.xk.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
@EnableCaching
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());

        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();

        return template;
    }

    /**
     * 对hash类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 对redis字符串类型数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 对链表类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 对无序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 对有序集合类型的数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }

}

使用Redis
/*
使用注解
@Cacheable(value = "userList")
可以标记在一个方法上,也可以标记在一个类上,当标记的方法上时该方法支持缓存的,当标记在一个类上时则表示当前类的所有方法都支持缓存,对于一个支持缓存方法,Spring会在其被调用(查询数据库)后将返回值缓存起来,以保证下次利用同样是参数执行该方法时可以直接从缓存中获取value=名称
key=属性用来指定Spring缓存方法的返回结果时对应的key
@CachePut:主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和Cacheable不同的是,它每次都会触发真实方法的调用;这个注释可以确保方法被执行,同时方法的返回值也被记录到缓存中,实现缓存与数据库的同步更新
@CacheEvict(value="key",allEntries=true,beforeInvocation=true)
用来标注 需要清楚缓存的方法 或 类上,能够根据一定的条件对缓存进行清空
value:缓存的名字
allEntries=true:是boolean表示是否需要清楚缓存中的所有元素,默认为false
beforeInvocation=true 属性 清除操作 默认是在对应方法执行之前触发
*/
静态资源找不到
#   “spring.mvc.static-path-pattern”用于阐述HTTP请求地址,请求非controller地址,如js,css,img等访问路径需要加上static,
# 可以不配置也能访问图片
#  而“spring.resources.static-locations”则用于描述静态资源的存放位置。多个路径(逗号隔开)中依次查找是否存在
spring:
  mvc:
    static-path-pattern: /static/**
  resources:
    static-locations: classpath:/static/
//方法一  
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebAppConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
        super.addResourceHandlers(registry);
    }
}

//方法二  在maven中配置静态资源
<resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*</include>
                </includes>
            </resource>
</resources>
Mybatis代码生成器
<!--在pom文件中导入mybatis generator依赖并添加mybatis generator maven 插件-->
<!--使用mybatis generator 生成代码-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>
        
        
        <!--添加mybatis generator maven 插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <!--配置-->
                <configuration>                    		<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <phase>generate-sources</phase>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <scope>runtime</scope>
                        <version>5.1.10</version>
                    </dependency>
                </dependencies>
            </plugin>
<!-- 配置generatorConfig.xml文件 -->

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
    <!--执行generator插件生成文件的命令: call mvn mybatis-generator:generate -e -->
    <!-- 引入配置文件 -->
    <properties resource="mybatisGeneratorinit.properties"/>
    <!-- 一个数据库一个context -->
    <!--defaultModelType="flat" 大数据字段,不分表 -->
    <context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;
        一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
        <property name="autoDelimitKeywords" value="true"/>
        <!-- 生成的Java文件的编码 -->
        <property name="javaFileEncoding" value="utf-8"/>
        <!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>

        <!-- 格式化java代码 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化XML代码 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>

        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>

        <!-- 注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
            <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳-->
        </commentGenerator>

        <!-- jdbc连接 -->
        <jdbcConnection driverClass="${jdbc_driver}" connectionURL="${jdbc_url}" userId="${jdbc_user}"
                        password="${jdbc_password}"/>
        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 注意!!!!     生成实体类地址是自己的项目地址中的实体类位置 -->
        <javaModelGenerator targetPackage="com.xk.pojo" targetProject="E:\IdeaProjects\springboot_t1\src\main\java">
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 注意!!!!      生成mapperxml文件是自己的项目地址中的mapperxml位置 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="E:\IdeaProjects\springboot_t1\src\main\resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 注意!!!!      生成mapxml对应client,是自己的项目地址中的dao层位置 -->
        <javaClientGenerator targetPackage="com.xk.mapper" targetProject="E:\IdeaProjects\springboot_t1\src\main\java" type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!-- table可以有多个,每个数据库中的表都可以写一个table,
        tableName表示要匹配的数据库表,也可以在
        tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 -->
        <!--如果想生成一个表则tableName="table_name"-->
        <table tableName="%"
               enableCountByExample="true"
               enableUpdateByExample="true"
               enableDeleteByExample="true"
               enableSelectByExample="true"
               selectByExampleQueryId="true">
            <property name="useActualColumnNames" value="false"/>
            <!-- 数据库表主键 -->
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>
## 配置mybatisGeneratorinit.properties文件  数据库信息
jdbc_driver=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/appinfodb?useUnicode=true&characterEncoding=utf-8&useSSL=true
jdbc_user=root
jdbc_password=root
一键生成实体类,mapper.xml文件,dao层

在这里插入图片描述

热部署
热部署的作用就是,修改代码之后,可以不需要重新启动项目的情况下能够自动启动,将修改的代码编译并部署到服务器上
,使得修改立即生效。
<!--在pom文件中导入spring boot 热部署依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>
#在application.yml文件中配置热部署
spring:
  devtools:
    restart:
      enabled: true #开启热部署
      additional-paths: src/main/java  #只要修改这个目录下的代码就会重新启动
      exclude: templates/** #修改前端页面不需要重新启动
  freemarker:
    cache: false #页面缓存不加载,修改立即生效
idea设置

在这里插入图片描述

2.ctrl+shift+alt+/ 选择registry

在这里插入图片描述

Swagger
Swagger是一个规范和完整的框架,用于生成,描述,调用和可视化的Restful风格web服务
作用:接口的文档在线生成、功能测试
在pom文件中导入依赖

在这里插入图片描述

创建配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()).select()
                /*当钱包 路径*/
                .apis(RequestHandlerSelectors.basePackage("com.xk"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                /*页面标题*/
                .title("SpringBoot测试 使用swagger2 构建 RESTful API文档")
                /*创建人*/
                /*.contact(new Contact("XXXX名字","https://localhost:8080/springboot/swagger-ui.html","xxxx@163.com"))*/
                .termsOfServiceUrl("http://localhost:8080/springboot/swagger-ui.html")
                /*版本号*/
                .version("1.0")
                .description("API 描述")
                .build();
    }
}

通过注解类,注解方法,参数

在这里插入图片描述

访问swagger-ui页面

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当前课程中博客项目的实战源码是我在 GitHub上开源项目 My-Blog,目前已有 3000 多个 star:本课程是一个 Spring Boot 技术栈的实战类课程,课程共分为 3 大部分,前面两个部分为基础环境准备和相关概念介绍,第三个部分是 Spring Boot 个人博客项目功能的讲解,通过本课程的学习,不仅仅让你掌握基本的 Spring Boot 开发能力以及 Spring Boot 项目的大部分开发使用场景,同时帮你提前甄别和处理掉将要遇到的技术难点,认真学完这个课程后,你将会对 Spring Boot 有更加深入而全面的了解,同时你也会得到一个大家都在使用的博客系统源码,你可以根据自己的需求和想法进行改造,也可以直接使用它来作为自己的个人网站,这个课程一定会给你带来巨大的收获。作者寄语本课程录制于 2020 年,代码基于 Spring Boot 2.x 版本。到目前为止,Spring Boot 技术栈也有一些版本升级,比如 Spring Boot 2.7 发版、Spring Boot 3.x 版本发布正式版本。对于这些情况,笔者会在本课程实战项目的开源仓库中创建不同的代码分支,保持实战项目的源码更新,保证读者朋友们不会学习过气的知识点。课程特色 课程内容紧贴 Spring Boot 技术栈,涵盖大部分 Spring Boot 使用场景。开发教程详细完整、文档资源齐全、实验过程循序渐进简单明了。实践项目页面美观且实用,交互效果完美。包含从零搭建项目、以及完整的后台管理系统和博客展示系统两个系统的功能开发流程。技术栈新颖且知识点丰富,学习后可以提升大家对于知识的理解和掌握,对于提升你的市场竞争力有一定的帮助。实战项目预览    

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值