SpringBoot笔记(二次学习)

本文详细介绍SpringBoot的入门知识,包括其简化Spring应用开发的优势、微服务概念、快速搭建项目、部署方式、自动配置原理及实践案例。涵盖SpringBoot与Web开发、日志框架、数据访问等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot笔记

SpringBoot入门

一、简介

SpringBoot来简化Spring应用开发,约定大于配置,去繁从简

二、优点

  • 快速创建Spring项目

  • 使用嵌入式Servlet容器,无需打成war包

  • starters自动依赖与版本控制

  • 大量的自动配置,简化开发

  • 无需配置xml

    。。。

三、缺点

入门简单,深入困难

四、微服务

微服务:架构风格

一个应用就是一组小型服务;可以通过HTTP的方式互通;

每一个功能元素最终都是一个可独立替换和独立升级的软件单元;

五、浏览器输出Hello Word

@Controller
public class HelloWordController {

  @RequestMapping("/hello")
  public @ResponseBody
  String
  hello() {
    return "Hello Word";
  }
}
@SpringBootApplication
public class SpringBootHellowordApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootHellowordApplication.class, args);
  }

}

简化部署

<!--将应用打包成一个可执行的jar包-->
<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
  </plugins>
</build>

将这个应用打成jar包,直接使用java -jar的命令进行执行

六、Hello Word探究

pom文件

1、父项目

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

所以导入依赖默认是不需要写版本的;(没有在dependencies里面管理的依赖自然需要声明版本号)

导入的依赖

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

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

Spring Boot将所有的功能场景都抽取出来,做成一个个starters(启动器),只需要在项目里面引入这些starter相关场景的所有依赖都会导入进来。要用什么功能酒倒入什么场景的启动器

主程序类,主入口类

//标注主程序类
@SpringBootApplication
public class SpringBootHellowordApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringBootHellowordApplication.class, args);
  }

}

@SpringBootApplication:Spring Boot应用标注在某一个类上说明这个类是SpringBoot的朱配置类,SpringBoot就是应该运行这个类的main方法来启东SpringBoot应用;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
  excludeFilters = {@Filter(
  type = FilterType.CUSTOM,
  classes = {TypeExcludeFilter.class}
), @Filter(
  type = FilterType.CUSTOM,
  classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
  • @SpringBootConfiguration:Spring Boot的配置类;标注在某个类上,表示这个一个Spring Boot的配置类;

    • @Configuration:配置类上来标注这个注解;配置类《==》配置文件;当然这也是一个组件(@Component)
  • @EnableAutoConfiguration:开启自动配置功能;以前我们需要配置的东西,Spring Boot帮我们自动配置;

    • @AutoConfigurationPackage:自动配置包

      • @Import({Registrar.class})
        

        Spring的底层注解@Import,给容器中导入一个组件;导入的组件由@Import({Registrar.class})

        将主配置类(@SpringBootApplication)的所在包及下面所有子包里面的所有组件扫描到Spring容器;

    • @Import({AutoConfigurationImportSelector.class}):导入那些组件的选择器;将所有需要导入的组件以全类名的方式返回;这些组件就会被添加到容器中;会给容器中导入非常多的自动配置类(xxxAutoConfiguration);就是给容器中导入这个场景需要的所有组件,并配置好这些组件

      • public String[] selectImports(AnnotationMetadata annotationMetadata) {
        

      if (!this.isEnabled(annotationMetadata)) {
      return NO_IMPORTS;
      } else {
      AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
      return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
      }
      }
      ```

      有了自动配置类,免去了我们手动编写配置注入功能组件等的工作;
      
      getCandidateConfigurations(annotationMetadata, attributes)-->SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader())-->loadSpringFactories(@Nullable ClassLoader classLoader)-->getResources("==META-INF/spring.factories==")
      
      从而在==META-INF/spring.factories==中获取EnableAutoConfiguration指定的值,将这些值作为自动配置类导入到容器中,自动配置类就生效了,帮我们进行自动配置工作;以前我们需要自己配置的东子,自动配置类帮我们完成了;
      

七、使用Spring Initializer快速创建Spring Boot项目

IDEA创建即可

默认生成的Spring Boot项目:

  • 主程序已经生成好了,我们只需要添加我们自己的逻辑
  • resources文件夹中目录结构
    • static:保存所有的静态资源:js css images;
    • templates:保存所有的模板页面:(Spring Boot默认jar包使用嵌入式的Tomcat,默认不支持jsp);可以使用模板引擎(freemarker,thymeleaf)
    • applicatgion.properties:配置文件;

SpringBoot配置文件

1.配置文件

SpringBoot使用一个全局的配置文件,配置文件名都是固定的

  • application.properties
server.port=8081
  • application.yml
server:
  port: 8081

配置文件的作用:修改SpringBoot自动配置的默认值;

2、yaml基本语法

  • key:(空格)value
  • 左对齐的一列数据,都是同一个层级的
  • 大小写敏感
值的写法
  • 字面量:普通的值

k: v

字符串默认不用加上单引号,或者双引号

” “:不会转义字符串里面的特殊字符;特殊字符会作为本身想表达的思想(\n会换行)

‘ ’:会转义(\n就是\n)

  • 对象、Map(键值对)

k: v

friends:
    lastName:zhangsan
    age:20

行内写法:

friends:{lastName:zhangsan,age:20}
  • 数组(List、Set)

用-值表示数组中的一个元素

pets:
 - cat
 - dog
 - pig

行内写法:

pets:[cat,dog,pig]

@ConfigurationProperties(prefix=“person”):告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;

@Value("${person.lastName}")

@ConfigurationProperties@Value
功能批量注入配置文件中的属性一个个指定
松散绑定支持不支持
SpEL不支持支持
JSR303数据校验支持不支持
复杂类型支持不支持

@PropertySource:指定配置文件

@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效;

SpringBoot推荐给容器中添加组件的方式:推荐使用注释(@Configuration)的方式

3、配置文件占位符

  • 随机数

${random.uuid}

  • 占位符获取之前配置的值,如果没有可以是用:指定默认值
person.age=1
person.name=zhangsan
person.dog.name=${person.name:noName}_dog

4、Profile

1、多Profile文件

我们在主配置文件编写的时候,文件名可以是application-{profile}.properties/yml

默认使用application.properties的配置;

2、yml支持多文档块方式
spring:
  profiles:
    active: prod
server:
  prot: 8081
---
server:
  port: 8082
spring:
  profile: dev
---
server:
  port:8083
spring:
  profile:prod
3、激活指定profile

1、在配置中指定spring.profiles.active=dev(yaml格式相应改变即可)

2、命令行:

–spring.profiles.active=dev

3、虚拟机参数

-Dspring.profiles.active=dev

4、配置文件加载优先级(从高到低)

-file:./config/

-file:./

-classpath:/config/

-classpath:/

SpringBoot会从这四个位置全部加载主配置文件;并互补配置;

spring.config.location改变默认配置位置,在打包后配合命令行实现配置互补

5、外部配置加载顺序

用到时候在查即可

5、自动配置原理

1、自动配置原理:
2、细节(@ConditionalOnMissingBean等等)

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

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

自动配置类必须在一定的条件下才能生效

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

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

SpringBoot与日志

1、日志框架

日志门面(日志抽象层)日志实现
JCL,SLF4j,jboss-loggingLog4j,JUL,Log4j2,Logback

左边选一个门面,右边选一个实现

日志门面:SLF4J;

日志实现:Logback;

SpringBoot:底层是Spring框架,SPring框架默认是JCL;

SpringBoot选用SLF4j和logback;

2、SLF4j使用

以后开发的时候,日志记录方法的调用,你应该直接调用日志的实现类,而是调用日志抽象层呢个里面的方法;

给系统里面导入slf4j的jar和logback的实现jar

每一个日志的实现框架都有自己的配置文件;使用slf4j以后,配置文件还是日志实现框架自己本身的配置文件

3、遗留问题

a(slf4j+logback):Spring(commons-logging)、Hibernate(jboss-logging)、Mybatis、xxxxx

统一日志记录,即使是别的框架也能和一起统一使用slf4j进行输出?

1、将系统中其他日志框架先排除出去;

2、用中间包来替换原有的日志框架;

3、导入slf4j其他的实现

4、日志使用;

具体代码

 Logger logger = LoggerFactory.getLogger(getClass());
//    trace<debug<info<warn<error
    logger.trace("这是trace");
    logger.debug("这是debug");
    logger.info("这是info");
    logger.warn("这是warn");
    logger.error("这是error");

配置文件

server.port=8081
logging.level.com.example=trace
#不指定路径在当前项目下生成springboot.log日志
#可以指定完整的路径
logging.file.name=E:/springboot.log
#在当前磁盘的根路径下创建spring文件夹和里面的log文件夹:使用spring.log作为默认文件
logging.file.path=/spring/log
#在控制台输出的日志的格式
logging.pattern.console=%{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
#指定文件中日志输出的格式
logging.pattern.file=%{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n

logback.xml:直接就被日志框架识别了

logback-spring.xml:日志矿机就不直接加载日志的配置项,由SpringBoot解析日志配置,可以使用SpringBoot的高级Profile功能

SpringBoot与Web开发

1.大致流程

1)创建SpringBoot应用,选中我们需要的模块;

2)SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来

xxxxAutoConfiguration:帮我们给容器中自动配置组件;

xxxxProperties:配置类中封装配置文件的内容;

3)自己编写业务代码;

2.SpringBoot对静态资源的映射规则

1)webjars:以jar包的方式引入静态资源;

所有/webjars/**,都去classpath:/META-INF/resources/webjars/找资源;

<!--    jquery静态资源-->
<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>jquery</artifactId>
  <version>3.3.1</version>
</dependency>

localhost:/8080/webjars/jquery/3.3.1/jquery.js

2)“/**”访问当前项目的任何资源,(静态资源的文件夹)

classpath:/META-INF/resources/
classpath:/resources/
classpath:/static/
classpath:/public/
/:当前项目的根路径

localhost:8080/abc === 去静态资源文件夹里面寻找abc

3)欢迎页

静态资源文件夹下的所有index.html页面;被“/**”映射;

localhost:/8080/

4)图标

所有的**/favicon.ico都是在静态资源文件下找;

模板引擎

jsp,freemarker,thymeleaf

SpringBoot推荐的Thymeleaf:语法简单,功能强大

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

Thymeleaf用法

放在classpath:/templates/下,thymeleaf就能自动渲染

使用

1.导入thymeleaf命名空间

<html lang="en" xml:th="http://www.thymeleaf.org">

2.初体验

@Controller
public class HelloController {

  @RequestMapping("/hello")
  public String hello(Model model) {
    model.addAttribute("hello", "hello thymeleaf");
    return "test";
  }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h1>成功</h1>
<!--将div里面的文本内容设置为-->
<div th:text="${hello}"></div>
</body>
</html>

3.语法规则

1)th:text;改变当前元素里面的内容

th:任意html属性;替换原生属性的值

image-20200601100055465

2)表达式

${...}:获取变量值OGNL
    1):获取对象的属性,调用方法
    2):使用内置对象
	3):内置的一些工具对象
*{...}:选择表达式,和${}在功能上是一样的
	配合${...}使用:
	<div th:object="${session.user}"> 
	<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p> 
	<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> 
	<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p> 
	</div>
#{...}:获取国际化内容
@{...}:定义URL
	<a href="details.html"
	th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view
	</a>
~{}:片段引用表达式
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: _

SpringBoot对SpringMVC的默认配置

  • 自动配置了视图解析器(根据方法的返回值的到视图对象,视图对象决定如何渲染(转发?重定向?));如何定制:自己给容器添加一个视图解析器;自动的将其组合起来;

  • 静态首页访问

  • favicon.ico

  • 自动注册Converter(转换器:类型转换使用Converter);Formatter(格式化器:2017.12.17==Date);

  • HttpMessageConverter:SpringMVC用来转换Http请求和响应的;User对象–Json;

  • 错误代码生成规则

  • 数据绑定

扩展SpringMVC

编写配置类(@Configuration)继承WebMvcConfigurerAdapter

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
//    super.addViewControllers(registry);
    registry.addViewController("/failed").setViewName("success");
  }
}

既保留了所有的自动配置,也能用我们扩展的配置

原理:

1.WebMvcAutoConfiguration是SpringMVC的自动配置类

2.在做其他自动配置时会导入;@Import(EnableWebMvcConfiguration.class)

3.容器中所有的WebMvcConfigurer都会一起起作用

4.我们中所有的WebMvcConfigurer

全面接管SpringMVC

@EnableWebMvc:SpringBoot对SpringMVC的自动配置不需要了,都要自己配

修改SpringBoot的默认配置

1)SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean,@Controller)如果有就用用户配置的,如果没有,才自动配置;如果有些组件(ViewResolver)有多个将用户配置的和自己默认的组合起来;

RestfulCRUD实验

1)默认访问首页
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

  @Bean
  public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
    WebMvcConfigurerAdapter adapter=new WebMvcConfigurerAdapter() {
      @Override
      public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
      }
    };
    return adapter;
  }
}
2)国际化

以前jsp

1)编写国际化配置文件;

2)使用ResourceBundleMessageSource管理国际化资源文件

3)在页面使用fmt:message取出国际化内容

现在

步骤:

1)编写国际化配置文件,抽取页面需要显示的国际化消息;

index.properties

index_zh_CN.properties

index_en_US.properties

2)SpringBoot自动配置好了管理国际化资源文件的组件;

spring.messages.basename=il8n/index

3)页面获取国际化的值;

#{login.username}
[[#{login.remember}]]
...

原理:

国际化Locale(区域消息对象);LocaleResolver(获取区域消息对象);

默认的就是根据请求头带来的区域消息获取Locale进行国际化

Accept-Language:zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7

3)登陆

开发期间模板引擎页面修改以后,要实时生效

1)禁用模板引擎的缓存

#禁用模板引擎缓存
spring.thymeleaf.cache=false

2)页面修改完成以后ctrl+f9:重新编译;

登陆错误信息的显示

<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

3)拦截器进行登陆检查

public class Interceptor implements HandlerInterceptor {

  //目标方法执行之前
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    Object user = request.getSession().getAttribute("loginUser");
    if (user == null) {
      request.setAttribute("msg", "没有权限请先登录");
      request.getRequestDispatcher("/index.html").forward(request, response);
      return false;
    }
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {

  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) throws Exception {

  }
}


 @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new Interceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/login");
  }
4)CRUD-员工列表
普通CRUDRestfulCRUD
查询getEmpemp-GET
添加addEmp?xxxemp-POST
修改updateEmp?id=xxx&xxx=xxemp/{id}-PUT
删除deleteEmp?id=xxemp/{id}-DELETE
请求URI请求方式
查询所有员工empsGET
查询某个员工(信息回显)emp/1GET
来到添加页面empGET
添加员工empPOST
来到修改页面(信息回显)emp/1GET
修改员工empPUT
删除员工emp/1DELETE
thymeleaf公共页面元素抽取

1)抽取公共片段

<nav class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0" th:fragment="topbar">
			<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">[[${session.loginUser}]]</a>
			<input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
			<ul class="navbar-nav px-3">
				<li class="nav-item text-nowrap">
					<a class="nav-link" href="http://getbootstrap.com/docs/4.0/examples/dashboard/#">Sign out</a>
				</li>
			</ul>
		</nav>

2)引用公共片段

<div th:insert="~{dashboard::topbar}"></div>

3)默认效果

insert的公共片段在div标签中

三种引入公共片段的th属性:

th:insert(公共片段整个插入到声明的引入的元素中)

th:replace(将声明引入的元素替换为公共片段)

th:include(将被引入的片段的内容包含进这个标签中)

引入片段的时候传入参数:

<div th:replace="commons/bar::#sidebar(activeUri='main')"></div>
<a class="nav-link" href="#"   th:class="${activeUri=='emps'?'nav-link active':'nav-link'}" th:href="@{/emps}">

提交的数据格式不对:日期等等

2012/12/12;2012-12-12;2021.12.12

日期的格式化:SpringMvc将页面提交的值需要转换未指定的类型

spring.mvc.format.date=yyyy-MM-dd

5)错误处理机制

SpringBoot默认的错误处理机制

1)如果浏览器,返回一个默认的错误页面

如果是其他客户端,默认响应一个json数据

原理:

参照ErrorMVCAutoConfiguration;错误处理的自动配置;

1、DefaultErrorAttrtibutes:

帮我们在页面获取值

2、BasicErrorController:

@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {
    
    @RequestMapping(
    produces = {"text/html"}//产生html类型的数据;浏览器返送的请求来到这个方法处理
  )
  public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
    HttpStatus status = this.getStatus(request);
    Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
    response.setStatus(status.value());
      //去哪个页面作为错误页面;包含页面地址和页面内容
    ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
    return modelAndView != null ? modelAndView : new ModelAndView("error", model);
  }

  @RequestMapping//产生json数据;其他客户端来到这个方法处理
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    HttpStatus status = this.getStatus(request);
    if (status == HttpStatus.NO_CONTENT) {
      return new ResponseEntity(status);
    } else {
      Map<String, Object> body = this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.ALL));
      return new ResponseEntity(body, status);
    }
  }

3、ErrorPageCustomizer:

public class ErrorProperties {
  @Value("${error.path:/error}")

4、DefaultErrorViewResolver:

public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
  ModelAndView modelAndView = this.resolve(String.valueOf(status.value()), model);
  if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
    modelAndView = this.resolve((String)SERIES_VIEWS.get(status.series()), model);
  }

  return modelAndView;
}

private ModelAndView resolve(String viewName, Map<String, Object> model) {
    //默认SpringBoot可以找到一个页面error/404
  String errorViewName = "error/" + viewName;
   //如果模板引擎可以解析这个页面地址就用模板引擎解析
  TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);
    //模板引擎可用的情况下返回到errorViewName指定的视图地址,模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html
  return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model);
}

步骤:

一旦系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则);就会来到/error请求;就会被BasicErrorController处理;

2)如何定制错误响应;

  • 如何定制错误的页面

​ 1)、有模板引擎的情况下;error/状态码.html【将错误页面命名为错误状态码.html放在模板引擎文件夹下的error文件夹下】,发生此状态码的错误就会来到对应页面;可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态码.html)

​ 2)、没有模板引擎的情况下:(模板引擎找不到这个错误页面),静态资源文件夹下找

​ 3)、都没有,则到SpringBoot默认的错误提示页面

  • 如何定制错误的json数据

1)、自定义异常处理&返回定制json数据

2)、转发到/error进行自适应效果处理

3)、将我们的定制数据携带出去

6)配置嵌入式Servlet容器

SpringBoot默认是使用嵌入式的Servlet容器(Tomcat);

1)如何定制和修改Servlet容器的相关配置

1、修改和server有关的配置

server.port=8081
server.servlet.context-path=/crud

2、编写一个EmbeddedServletContainerCustomizer:嵌入式的Servlet容器的定制器;

2)注册Servlet三大组件【Servlet,Filter,Listener】

由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SPringBoot的Web应用,没有web.xml文件

注册三大组件用以下方式

ServletRegistrationBean

FilterRegistrationBean

ServletListenerRegistrationBean

3)SpringBoot能否支持其他Servlet容器

可以

SpringBoot与Docker

简介

Docker是一个开源的应用容器引擎

Docker支持将软件编译成一个镜像;然后在镜像中各种软件做好配置,将镜像发布出去,其他使用者可以直接使用这个镜像;

运行中的这个镜像称之为容器,容器启动是非常快速的

核心概念

docker主机(Host):安装了Docker程序的机器(Docker直接安装在操作系统之上)

docker客户端(Client):连接docker主机进行操作

docker仓库:保存打包好的软件镜像

docker镜像:软件打包好的镜像

docker容器:镜像启动后的实例

使用Docker的步骤:

1)、安装Docker

2)、去Docker仓库找到这个软件对应的镜像

3)、使用Docker运行这个镜像,这个镜像就会生成一个Docker容器;

SpringBoot和数据访问

1、jdbc

spring:
  datasource:
    username: root
    password: 761020zy
    url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

自动建表,默认只需要将文件命名为:

scheme-*.sql

data-*.sql

操作数据库:

@GetMapping("/query")
public @ResponseBody
List<Map<String, Object>> query() {
  List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from account");
  return list;
}

2、整合Druid数据源

导入druid数据源
@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
       return  new DruidDataSource();
    }

    //配置Druid的监控
    //1、配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String,String> initParams = new HashMap<>();

        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow","");//默认就是允许所有访问
        initParams.put("deny","192.168.15.21");

        bean.setInitParameters(initParams);
        return bean;
    }


    //2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }
}

3、整合MyBatis

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

步骤:

1)、配置数据源相关属性(见上一节Druid)

2)、给数据库建表

3)、创建JavaBean

4)、注解版

//指定这是一个操作数据库的mapper
@Mapper
public interface DepartmentMapper {

    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true,keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

问题:

自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer;

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){

            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}
使用MapperScan批量扫描所有的Mapper接口;
@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
	}
}

5)、配置文件版

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml 指定全局配置文件的位置
  mapper-locations: classpath:mybatis/mapper/*.xml  指定sql映射文件的位置

)
public int insertDept(Department department);

@Update("update department set departmentName=#{departmentName} where id=#{id}")
public int updateDept(Department department);

}


问题:

自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer;

```java
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){

            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}
使用MapperScan批量扫描所有的Mapper接口;
@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
	}
}

5)、配置文件版

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml 指定全局配置文件的位置
  mapper-locations: classpath:mybatis/mapper/*.xml  指定sql映射文件的位置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小赵OvO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值