SpringBoot学习总结

学习准备

使用 IDEA 直接创建项目

1、创建一个新项目

2、选择spring initalizr  可以看到默认就是去官网的快速构建工具那里实现

3、填写项目信息

4、选择初始化的组件

5、填写项目路径

6、等待项目构建成功

项目创建成功

pom文件的主要依赖

启动器 spring-boot-starter

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

springboot-boot-starter-xxx:就是spring-boot的场景启动器

spring-boot-starter-web:帮我们导入了web模块正常运行所依赖的组件;

SpringBoot将所有的功能场景都抽取出来,做成一个个的starter (启动器),只需要在项目中引入这些starter即可,所有相关的依赖都会导入进来 , 我们要用什么功能就导入什么样的场景启动器即可 ;我们未来也可以自己自定义 starter;

SpringApplication.run分析

分析该方法主要分两部分,一部分是SpringApplication的实例化,二是run方法的执行;

yaml概述

YAML是 "YAML Ain't a Markup Language" (YAML不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言)

对象、Map(键值对)

#对象、Map格式k:     v1:    v2:

在下一行来写对象的属性和值得关系,注意缩进;比如:

student:    name: qinjiang    age: 3

行内写法

student: {name: qinjiang,age: 3}

数组( List、set )

用 - 值表示数组中的一个元素,比如:

pets: - cat - dog - pig

行内写法

pets: [cat,dog,pig]

yaml注入配置文件

使用yaml配置的方式进行注入编写一个yaml配置!

person:  name: qinjiang  age: 3  happy: false  birth: 2000/01/01  maps: {k1: v1,k2: v2}  lists:   - code   - girl   - music  dog:    name: 旺财    age: 1

/*@ConfigurationProperties作用:将配置文件中配置的每一个属性的值,映射到这个组件中;告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定参数 prefix = “person” : 将配置文件中的person下面的所有属性一一对应*/@Component //注册bean@ConfigurationProperties(prefix = "person")public class Person {    private String name;    private Integer age;    private Boolean happy;    private Date birth;    private Map<String,Object> maps;    private List<Object> lists;    private Dog dog;}

IDEA 提示,springboot配置注解处理器没有找到,让我们看文档,我们可以查看文档,找到一个依赖!

图片

图片

<!-- 导入配置文件处理器,配置文件进行绑定就会有提示,需要重启 --><dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-configuration-processor</artifactId>  <optional>true</optional></dependency>

9、确认以上配置都OK之后,我们去测试类中测试一下:

@SpringBootTestclass DemoApplicationTests {
    @Autowired    Person person; //将person自动注入进来
    @Test    public void contextLoads() {        System.out.println(person); //打印person信息    }
}

JSR303数据校验

先看看如何使用

Springboot中可以用@validated来校验数据,如果数据异常则会统一抛出异常,方便异常中心统一处理。我们这里来写个注解让我们的name只能支持Email格式;

@Component //注册bean@ConfigurationProperties(prefix = "person")@Validated  //数据校验public class Person {
    @Email(message="邮箱格式错误") //name必须是邮箱格式    private String name;}

运行结果 :default message [不是一个合法的电子邮件地址];

图片

使用数据校验,可以保证数据的正确性;

常见参数

@NotNull(message="名字不能为空")private String userName;@Max(value=120,message="年龄最大不能查过120")private int age;@Email(message="邮箱格式错误")private String email;
空检查@Null       验证对象是否为null@NotNull    验证对象是否不为null, 无法查检长度为0的字符串@NotBlank   检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.@NotEmpty   检查约束元素是否为NULL或者是EMPTY.    Booelan检查@AssertTrue     验证 Boolean 对象是否为 true  @AssertFalse    验证 Boolean 对象是否为 false      长度检查@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  @Length(min=, max=) string is between min and max included.
日期检查@Past       验证 Date 和 Calendar 对象是否在当前时间之前  @Future     验证 Date 和 Calendar 对象是否在当前时间之后  @Pattern    验证 String 对象是否符合正则表达式的规则
.......等等除此以外,我们还可以自定义一些数据校验规则

多配置文件

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

例如:

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

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

但是Springboot并不会直接启动这些配置文件,它默认使用application.properties主配置文件

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

#比如在配置文件中指定使用dev环境,我们可以通过设置不同的端口号进行测试;#我们启动SpringBoot,就可以看到已经切换到dev下的配置了;spring.profiles.active=dev

yaml的多文档块

和properties配置文件中一样,但是使用yml去实现不需要创建多个配置文件,更加方便了 !

server:  port: 8081#选择要激活那个环境块spring:  profiles:    active: prod
---server:  port: 8083spring:  profiles: dev #配置环境的名称

---
server:  port: 8084spring:  profiles: prod  #配置环境的名称

注意:如果yml和properties同时都配置了端口,并且没有激活其他环境 , 默认会使用properties配置文件的!

配置文件加载位置

外部加载配置文件的方式十分多,我们选择最常用的即可,在开发的资源文件中进行配置!

官方外部配置文件说明参考文档

图片

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

优先级1:项目路径下的config文件夹配置文件优先级2:项目路径下配置文件优先级3:资源路径下的config文件夹配置文件优先级4:资源路径下配置文件

我们在最低级的配置文件中设置一个项目访问路径的配置来测试互补问题;

#配置项目的访问路径server.servlet.context-path=/kuang

自动配置原理

配置文件到底能写什么?怎么写?

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

图片

分析自动配置原理

我们以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;  //如果不存在,判断也是成立的  //即使我们配置文件中不配置pring.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类中获取的,这些类里面的每一个属性又是和配置文件绑定的;

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

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

//从配置文件中获取指定的值和bean的属性进行绑定@ConfigurationProperties(prefix = "spring.http") public class HttpProperties {    // .....}

我们去配置文件里面试试前缀,看提示!

图片

这就是自动装配的原理!

精髓

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

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

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

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

xxxxAutoConfigurartion:自动配置类;给容器中添加组件

xxxxProperties:封装配置文件中相关属性;

了解:@Conditional

了解完自动装配的原理后,我们来关注一个细节问题,自动配置类必须在一定的条件下才能生效;

@Conditional派生注解(Spring注解版原生的@Conditional作用)

作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效;

图片

那么多的自动配置类,必须在一定的条件下才能生效;也就是说,我们加载了这么多的配置类,但不是所有的都生效了。

我们怎么知道哪些自动配置类生效?

我们可以通过启用 debug=true属性;来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效;

#开启springboot的调试类debug=true

Positive matches:(自动配置类启用的:正匹配)

Negative matches:(没有启动,没有匹配成功的自动配置类:负匹配)

Unconditional classes: (没有条件的类)

静态资源映射规则

ResourceProperties 可以设置和我们静态资源有关的参数;这里面指向了它会去寻找资源的文件夹,即数组的内容。

// 进入方法public String[] getStaticLocations() {    return this.staticLocations;}// 找到对应的值private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;// 找到路径private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {     "classpath:/META-INF/resources/",  "classpath:/resources/",     "classpath:/static/",     "classpath:/public/" };

我们也可以自己通过配置文件来指定一下,哪些文件夹是需要我们放静态资源文件的,在application.properties中配置;

spring.resources.static-locations=classpath:/coding/,classpath:/kuang/

欢迎页的映射,就是我们的首页!

@Beanpublic WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,                                                           FormattingConversionService mvcConversionService,                                                           ResourceUrlProvider mvcResourceUrlProvider) {    WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(        new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(), // getWelcomePage 获得欢迎页        this.mvcProperties.getStaticPathPattern());    welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));    return welcomePageHandlerMapping;}

点进去继续看

private Optional<Resource> getWelcomePage() {    String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());    // ::是java8 中新引入的运算符    // Class::function的时候function是属于Class的,应该是静态方法。    // this::function的funtion是属于这个对象的。    // 简而言之,就是一种语法糖而已,是一种简写    return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();}// 欢迎页就是一个location下的的 index.html 而已private Resource getIndexHtml(String location) {    return this.resourceLoader.getResource(location + "index.html");}

欢迎页,静态资源文件夹下的所有 index.html 页面;被 /** 映射。

比如我访问  http://localhost:8080/ ,就会找静态资源文件夹下的 index.html

新建一个 index.html ,在我们上面的3个目录中任意一个;然后访问测试  http://localhost:8080/  看结果!

关于网站图标说明

图片

与其他静态资源一样,Spring Boot在配置的静态内容位置中查找 favicon.ico。如果存在这样的文件,它将自动用作应用程序的favicon。

1、关闭SpringBoot默认图标

#关闭默认图标spring.mvc.favicon.enabled=false

2、自己放一个图标在静态资源目录下,我放在 public 目录下(命名favicon.ico)

Thymeleaf

怎么引入呢,对于springboot来说,什么事情不都是一个start的事情嘛,我们去在项目中引入一下。给大家三个网址:

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

Thymeleaf 在Github 的主页:https://github.com/thymeleaf/thymeleaf

Spring官方文档:找到我们对应的版本

https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter

找到对应的pom依赖:可以适当点进源码看下本来的包!

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

Thymeleaf的自动配置类:ThymeleafProperties

@ConfigurationProperties(    prefix = "spring.thymeleaf")public class ThymeleafProperties {    private static final Charset DEFAULT_ENCODING;    public static final String DEFAULT_PREFIX = "classpath:/templates/";    public static final String DEFAULT_SUFFIX = ".html";    private boolean checkTemplate = true;    private boolean checkTemplateLocation = true;    private String prefix = "classpath:/templates/";    private String suffix = ".html";    private String mode = "HTML";    private Charset encoding;}

导入命名空间的约束:xmlns:th="http://www.thymeleaf.org"

我们能写哪些表达式呢?

Simple expressions:(表达式语法)Variable Expressions: ${...}:获取变量值;OGNL;    1)、获取对象的属性、调用方法    2)、使用内置的基本对象:#18         #ctx : the context object.         #vars: the context variables.         #locale : the context locale.         #request : (only in Web Contexts) the HttpServletRequest object.         #response : (only in Web Contexts) the HttpServletResponse object.         #session : (only in Web Contexts) the HttpSession object.         #servletContext : (only in Web Contexts) the ServletContext object.
    3)、内置的一些工具对象:      #execInfo : information about the template being processed.      #uris : methods for escaping parts of URLs/URIs      #conversions : methods for executing the configured conversion service (if any).      #dates : methods for java.util.Date objects: formatting, component extraction, etc.      #calendars : analogous to #dates , but for java.util.Calendar objects.      #numbers : methods for formatting numeric objects.      #strings : methods for String objects: contains, startsWith, prepending/appending, etc.      #objects : methods for objects in general.      #bools : methods for boolean evaluation.      #arrays : methods for arrays.      #lists : methods for lists.      #sets : methods for sets.      #maps : methods for maps.      #aggregates : methods for creating aggregates on arrays or collections.==================================================================================
  Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;  Message Expressions: #{...}:获取国际化内容  Link URL Expressions: @{...}:定义URL;  Fragment Expressions: ~{...}:片段引用表达式
Literals(字面量)      Text literals: 'one text' , 'Another one!' ,…      Number literals: 0 , 34 , 3.0 , 12.3 ,…      Boolean literals: true , false      Null literal: null      Literal tokens: one , sometext , main ,…      Text operations:(文本操作)    String concatenation: +    Literal substitutions: |The name is ${name}|    Arithmetic operations:(数学运算)    Binary operators: + , - , * , / , %    Minus sign (unary operator): -    Boolean operations:(布尔运算)    Binary operators: and , or    Boolean negation (unary operator): ! , not    Comparisons and equality:(比较运算)    Comparators: > , < , >= , <= ( gt , lt , ge , le )    Equality operators: == , != ( eq , ne )    Conditional operators:条件运算(三元运算符)    If-then: (if) ? (then)    If-then-else: (if) ? (then) : (else)    Default: (value) ?: (defaultvalue)    Special tokens:    No-Operation: _

ContentNegotiatingViewResolver 内容协商视图解析器

自动配置了ViewResolver,就是我们之前学习的SpringMVC的视图解析器;

即根据方法的返回值取得视图对象(View),然后由视图对象决定如何渲染(转发,重定向)。

我们去看看这里的源码:我们找到 WebMvcAutoConfiguration , 然后搜索ContentNegotiatingViewResolver。找到如下方法!

@Bean
@ConditionalOnBean(ViewResolver.class)
@ConditionalOnMissingBean(name = "viewResolver", value = ContentNegotiatingViewResolver.class)
public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {
    ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
    resolver.setContentNegotiationManager(beanFactory.getBean(ContentNegotiationManager.class));
    // ContentNegotiatingViewResolver使用所有其他视图解析器来定位视图,因此它应该具有较高的优先级
    resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return resolver;
}

@Nullable // 注解说明:@Nullable 即参数可为null
public View resolveViewName(String viewName, Locale locale) throws Exception {
    RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
    Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
    List<MediaType> requestedMediaTypes = this.getMediaTypes(((ServletRequestAttributes)attrs).getRequest());
    if (requestedMediaTypes != null) {
        // 获取候选的视图对象
        List<View> candidateViews = this.getCandidateViews(viewName, locale, requestedMediaTypes);
        // 选择一个最适合的视图对象,然后把这个对象返回
        View bestView = this.getBestView(candidateViews, requestedMediaTypes, attrs);
        if (bestView != null) {
            return bestView;
        }
    }
    // .....
}

ContentNegotiatingViewResolver 这个视图解析器就是用来组合所有的视图解析器的

protected void initServletContext(ServletContext servletContext) {
    // 这里它是从beanFactory工具中获取容器中的所有视图解析器
    // ViewRescolver.class 把所有的视图解析器来组合的
    Collection<ViewResolver> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(this.obtainApplicationContext(), ViewResolver.class).values();
    ViewResolver viewResolver;
    if (this.viewResolvers == null) {
        this.viewResolvers = new ArrayList(matchingBeans.size());
    }
    // ...............
}

写一个视图解析器来试试;

@Bean //放到bean中public ViewResolver myViewResolver(){    return new MyViewResolver();}
//我们写一个静态内部类,视图解析器就需要实现ViewResolver接口private static class MyViewResolver implements ViewResolver{    @Override    public View resolveViewName(String s, Locale locale) throws Exception {        return null;    }}

扩展使用SpringMVC  官方文档如下:

If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.

我们要做的就是编写一个@Configuration注解类,并且类型要为WebMvcConfigurer,还不能标注@EnableWebMvc注解;我们去自己写一个;我们新建一个包叫config,写一个类MyMvcConfig;

@Configuration
public class MyMVCConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
        registry.addViewController("/test").setViewName("test");
    }
    @Bean
    public LocaleResolver localeResolver(){
        return  new MyLocaleResolve();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInceptorHandler()).excludePathPatterns("/index.html","/login","static/**","/");
    }
}

国际化

准备工作

先在IDEA中统一设置properties的编码问题!

项目结构

 

SpringBoot对国际化的自动配置!这里又涉及到一个类:MessageSourceAutoConfiguration

里面有一个方法,这里发现SpringBoot已经自动配置好了管理我们国际化资源文件的组件 ResourceBundleMessageSource;

// 获取 properties 传递过来的值进行判断@Beanpublic MessageSource messageSource(MessageSourceProperties properties) {    ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();    if (StringUtils.hasText(properties.getBasename())) {        // 设置国际化文件的基础名(去掉语言国家代码的)        messageSource.setBasenames(            StringUtils.commaDelimitedListToStringArray(                                       StringUtils.trimAllWhitespace(properties.getBasename())));    }    if (properties.getEncoding() != null) {        messageSource.setDefaultEncoding(properties.getEncoding().name());    }    messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());    Duration cacheDuration = properties.getCacheDuration();    if (cacheDuration != null) {        messageSource.setCacheMillis(cacheDuration.toMillis());    }    messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());    messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());    return messageSource;}

我们真实 的情况是放在了i18n目录下,所以我们要去配置这个messages的路径;

spring.messages.basename=i18n.login

配置国际化解析

在Spring中有一个国际化的Locale (区域信息对象);里面有一个叫做LocaleResolver (获取区域信息对象)的解析器!

我们去我们webmvc自动配置文件,寻找一下!看到SpringBoot默认配置:

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
    // 容器中没有就自己配,有的话就用用户配置的
    if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
        return new FixedLocaleResolver(this.mvcProperties.getLocale());
    }
    // 接收头国际化分解
    AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
    localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
    return localeResolver;
}

 AcceptHeaderLocaleResolver 这个类中有一个方法

public Locale resolveLocale(HttpServletRequest request) {
    Locale defaultLocale = this.getDefaultLocale();
    // 默认的就是根据请求头带来的区域信息获取Locale进行国际化
    if (defaultLocale != null && request.getHeader("Accept-Language") == null) {
        return defaultLocale;
    } else {
        Locale requestLocale = request.getLocale();
        List<Locale> supportedLocales = this.getSupportedLocales();
        if (!supportedLocales.isEmpty() && !supportedLocales.contains(requestLocale)) {
            Locale supportedLocale = this.findSupportedLocale(request, supportedLocales);
            if (supportedLocale != null) {
                return supportedLocale;
            } else {
                return defaultLocale != null ? defaultLocale : requestLocale;
            }
        } else {
            return requestLocale;
        }
    }
}
<a class="btn btn-sm" th:href="@{/index.html(url='zh_CN')}">中文</a>
|
<a class="btn btn-sm" th:href="@{/index.html(url='en_US')}">English</a>

处理类

package com.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

public class MyLocaleResolve implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String url = httpServletRequest.getParameter("url");
        Locale locale=Locale.getDefault();
        if(!StringUtils.isEmpty(url)){
            String[] split=url.split("_");
            locale=new Locale(split[0],split[1]);
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }

}

 为了让我们的区域化信息能够生效,我们需要再配置一下这个组件!在我们自己的MvcConofig下添加bean;

@Bean
    public LocaleResolver localeResolver(){
        return  new MyLocaleResolve();
    }

整合MyBatis测试

1、导入 MyBatis 所需要的依赖

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

 

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

2、配置数据库连接信息(不变)

spring:  datasource:    username: root    password: 123456    #?serverTimezone=UTC解决时区的报错    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8    driver-class-name: com.mysql.cj.jdbc.Driver    type: com.alibaba.druid.pool.DruidDataSource
    #Spring Boot 默认是不注入这些属性值的,需要自己绑定    #druid 数据源专有配置    initialSize: 5    minIdle: 5    maxActive: 20    maxWait: 60000    timeBetweenEvictionRunsMillis: 60000    minEvictableIdleTimeMillis: 300000    validationQuery: SELECT 1 FROM DUAL    testWhileIdle: true    testOnBorrow: false    testOnReturn: false    poolPreparedStatements: true
    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j    filters: stat,wall,log4j    maxPoolPreparedStatementPerConnectionSize: 20    useGlobalDataSourceStat: true    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3、测试数据库是否连接成功!

4、创建实体类,导入 Lombok!

Department.jav

package com.kuang.pojo;
import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;
@Data@NoArgsConstructor@AllArgsConstructorpublic class Department {
    private Integer id;    private String departmentName;
}

5、创建mapper目录以及对应的 Mapper 接口

DepartmentMapper.java

//@Mapper : 表示本类是一个 MyBatis 的 Mapper@Mapper@Repositorypublic interface DepartmentMapper {
    // 获取所有部门信息    List<Department> getDepartments();
    // 通过id获得部门    Department getDepartment(Integer id);
}

6、对应的Mapper映射文件

DepartmentMapper.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.kuang.mapper.DepartmentMapper">
    <select id="getDepartments" resultType="Department">       select * from department;    </select>
    <select id="getDepartment" resultType="Department" parameterType="int">       select * from department where id = #{id};    </select>
</mapper>

7、maven配置资源过滤问题

<resources>    <resource>        <directory>src/main/java</directory>        <includes>            <include>**/*.xml</include>        </includes>        <filtering>true</filtering>    </resource></resources>

Durid数据监控管理

1.添加上 Druid 数据源依赖。

<!-- https://mvnrepository.com/artifact/com.alibaba/druid --><dependency>    <groupId>com.alibaba</groupId>    <artifactId>druid</artifactId>    <version>1.1.21</version></dependency>

2、切换数据源;之前已经说过 Spring Boot 2.0 以上默认使用 com.zaxxer.hikari.HikariDataSource 数据源,但可以 通过 spring.datasource.type 指定数据

spring:
  datasource:
    username: root
    password: 123456
    #?serverTimezone=UTC解决时区的报错
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

配置Druid数据源监控

Druid 数据源具有监控的功能,并提供了一个 web 界面方便用户查看,类似安装 路由器 时,人家也提供了一个默认的 web 页面。

所以第一步需要设置 Druid 的后台管理页面,比如 登录账号、密码 等;配置后台管理;

//配置 Druid 监控管理后台的Servlet;
//内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
@Bean
public ServletRegistrationBean statViewServlet() {
    ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

    // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet 
    // 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
    Map<String, String> initParams = new HashMap<>();
    initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
    initParams.put("loginPassword", "123456"); //后台管理界面的登录密码

    //后台允许谁可以访问
    //initParams.put("allow", "localhost"):表示只有本机可以访问
    //initParams.put("allow", ""):为空或者为null时,表示允许所有访问
    initParams.put("allow", "");
    //deny:Druid 后台拒绝谁访问
    //initParams.put("kuangshen", "192.168.1.20");表示禁止此ip访问

    //设置初始化参数
    bean.setInitParameters(initParams);
    return bean;
}

配置完毕后,我们可以选择访问 :http://localhost:8080/druid/login.html

配置 Druid web 监控 filter 过滤器

//配置 Druid 监控 之  web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter() {
    FilterRegistrationBean bean = new FilterRegistrationBean();
    bean.setFilter(new WebStatFilter());

    //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
    Map<String, String> initParams = new HashMap<>();
    initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
    bean.setInitParameters(initParams);

    //"/*" 表示过滤所有请求
    bean.setUrlPatterns(Arrays.asList("/*"));
    return bean;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值