万字SpringBoot学习笔记|菜鸟版

2023年 7月 14日 62.8k 0

Spring Boot是Pivotal团队在Spring的基础上提供的一套全新的开源框架,其目的是为了简化Spring应用的搭建和开发过程。Spring Boot去除了大量的XML配置文件,简化了复杂的依赖管理。

官网地址:spring.io/projects/sp…

Spring Boot入门

简介

Spring Boot是简化Spring应用开发的一个框架、整个Spring技术栈的一个大整合(Spring全家桶时代)、J2EE开发的一站式解决方案(Spring Cloud是分布式整体解决方案)。优点:– 快速创建独立运行的Spring项目以及与主流框架集成– 使用嵌入式的Servlet容器,应用无需打成WAR包– starters自动依赖与版本控制– 大量的自动配置,简化开发,也可修改默认值– 无需配置XML,无代码生成,开箱即用– 准生产环境的运行时应用监控– 与云计算的天然集成

单体应用与微服务

– 单体应用:ALL IN ONE(所有内容都在一个应用里面)– 微服务:每一个功能元素最终都是一个可独立替换和独立升级的软件单元微服务是一种架构风格(服务微化),一个应用应该是一组小型服务,可以通过HTTP的方式进行互通

HelloWorld案例

工程创建及案例可以参考文章进行操作:在IDEA中创建SpringBoot项目

POM文件

父项目是Spring Boot的版本仲裁中心(他来真正管理Spring Boot应用里面的所有依赖版本),以后我们导入依赖默认是不需要写版本(没有在dependencies里面管理的依赖自然需要声明版本号)


    org.springframework.boot
    spring-boot-starter-parent
    2.7.11
     

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


    
        org.springframework.boot
        spring-boot-starter-web
    

    
        org.springframework.boot
        spring-boot-starter-test
        test
    

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

主程序类

// 自动生成的
@SpringBootApplication
public class SpringBootDemo0Application {
	public static void main(String[] args) {
		SpringApplication.run(SpringBootDemo0Application.class, args);
	}
}

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

Spring Boot配置

配置文件

SpringBoot使用一个全局的配置文件,配置文件名固定:application.properties 或者 application.yml。配置文件放在 src/main/resources目录 或者 类路径/config 下。作用是修改SpringBoot自动配置的默认值。

YAML

YAML(YAML Ain't Markup Language),.yml为结尾,以数据为中心,比json、xml等更适合做配置文件。

YAML配置例子
server:
    port: 8081

等价于XML配置:

    8081

【语法】key: value(注意冒号后面有个空格)以空格的缩进来控制层级关系,只要是左对齐的一列数据,都是同一个层级

【值写法】

(1)字面量:普通的值(数字,字符串,布尔)

  • k: v,字面量直接写
  • 字符串默认不用加上单引号或者双引号
  • ""(双引号),name: "zhangsan n lisi" 会输出 zhangsan 换行 lisi
  • ''(单引号),name: 'zhangsan n lisi' 会输出 zhangsan n lisi

(2)对象、Map

  • k: v,在下一行来写对象的属性和值
friends:
    lastName: zhangsan
	age: 20
或者:
friends: {lastName:zhangsan,age:18}

(3)数组(List、Set)

  • 用- 值表示数组中的一个元素
pets:
    ‐ cat
    ‐ dog
    ‐ pig
pets: [cat,dog,pig]

配置文件值注入 🔥

@ConfigurationProperties

1)导入配置文件处理器



	org.springframework.boot
	spring-boot-configuration-processor
	true

2)javaBean对象
@ConfigurationProperties(prefix = "person") 会将配置文件和类进行绑定:

/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
 *      prefix = "person":配置文件中哪个下面的所有属性进行一一映射
 * 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map maps;
    private List lists;
    private Dog dog;
	....
}

3)配置文件 application.yml

person:
  lastName: haha
  age: 18
  boss: false
  birth: 2022/01/01
  maps: {k1: v1,k2: v2}
  lists:
    - lisi
    - wangwu
  dog:
    name: 芒果
    age: 1

或者配置文件application.properties

#解决乱码问题
spring.message.encoding=UTF-8
#person
person.last-name=haha
person.age=20
person.birth=2022/01/02
person.boss=true
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=丸子
person.dog.age=5

乱码问题还需要配置:image.png
4)单元测试,先将内容注入(@Autowired)然后使用image.png

与@Value的区别

@ConfigurationProperties@Value 的区别:

  • @ConfigurationProperties 是批量注入配置文件中的属性,@Value 是一个个指定
  • @ConfigurationProperties 支持松散绑定(松散语法) 、不支持SpEL(表达式如#{2*4})、支持JSR303数据校验 、支持复杂类型封装(如map)
  • @Value 不支持松散绑定(松散语法) 、支持SpEL、不支持JSR303数据校验 、不支持复杂类型封装
@Component
// @ConfigurationProperties(prefix = "person")
public class Person {
    @Value("${person.last-name}")
    private String lastName;
    @Value("#{2*4}")
    private Integer age;
    @Value("true")
    private Boolean boss;
    @Value("${person.birth}")
    private Date birth;
    ...

松散绑定:– person.firstName:使用标准方式– person.first-name:大写用-– person.first_name:大写用_– PERSON_FIRST_NAME:推荐系统属性使用这种写法JSR303数据校验:image.png
使用规则:

  • 如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value
@Value("${febase.api.host}")
private String febaseHost;
  • 如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties

读取外部配置文件

@PropertySource:加载指定的配置文件

@PropertySource("classpath:person.properties")
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    ...
}

@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效--标注在一个配置类上如下我们自己编写的配置文件:




  

我们可以标注在主配置类上:

@SpringBootApplication
// 导入Spring的配置文件让其生效
@ImportResource(locations = {"classpath:beans.xml"})
public class SpringBootDemo0Application {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemo0Application.class, args);
    }
}

测试:

@SpringBootTest
class SpringBootDemo0ApplicationTests {
    @Autowired
    ApplicationContext ioc;

    @Test
    public void testHelloService(){
        boolean containsBean = ioc.containsBean("helloService");
        System.out.println(containsBean); 
        // 上一步没加@ImportResource之前返回false
        // 添加@ImportResource之后返回true
    }
}

SpringBoot推荐给容器中添加组件的方式,推荐使用全注解的方式 @Configuration

/**
 * @Configuration:指明当前类是一个配置类,就是来替代之前的Spring配置文件
 * 
 * 在配置文件中用标签添加组件。在配置类中使用@Bean注解
 */
@Configuration
public class MyAppConfig {
    // 将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService(){
        System.out.println("配置类@Bean给容器中添加组件了");
        return new HelloService();
    }
}

配置文件占位符

随机数

${random.value}、${random.int}、${random.long}、${random.uuid}
${random.int(10)}、${random.int[1024,65536]}

占位符获取之前配置的值,如果没有可以是用:指定默认值

#person
person.last-name=haha${random.uuid}
person.age=${random.int}
person.birth=2222/02/02
person.boss=false
person.maps.k1=v11111
person.maps.k2=v22222
person.lists=a,b,c,d,e,f
person.dog.name=${person.hello:hello}_dog
person.dog.age=1

Profile 🔥

Profile是Spring对不同环境提供不同配置功能的支持,可以通过激活、指定参数等方式快速切换环境。 多profile文件形式格式如:application-{profile}.properties/yml,如 application-dev.properties、application-prod.properties

默认使用application.properties的配置

激活方式:

  • 命令行 --spring.profiles.active=dev
    • java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;
  • 配置文件 spring.profiles.active=dev
  • jvm参数 –Dspring.profiles.active=dev

image.pngimage.pngyml支持多文档块方式:

server:
	port: 8081
spring:
	profiles:
	active: prod

‐‐‐
server:
	port: 8083
spring:
	profiles: dev

‐‐‐
server:
	port: 8084
spring:
	profiles: prod #指定属于哪个环境

配置文件加载位置

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

  • file:./config/
  • file:./
  • classpath:/config/
  • classpath:/
  • 以上是按照优先级从高到低的顺序,所有位置的文件都会被加载,高优先级配置内容会覆盖低优先级配置内容。 可以通过配置spring.config.location来改变默认配置。项目打包好以后,可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置;指定配置文件和默认加载的这些配置文件共同起作用形成互补配置:java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties

    外部配置加载顺序

    Spring Boot支持多种外部配置方式,优先级从高到低。高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置:

  • 命令行参数
  • 所有的配置都可以在命令行上进行指定:java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087 --server.context-path=/abc
  • 多个配置用空格分开; --配置项=值
  • 来自java:comp/env的JNDI属性
  • Java系统属性(System.getProperties())
  • 操作系统环境变量
  • RandomValuePropertySource配置的random.*属性值
  • 由jar包外向jar包内进行寻找。优先加载带profile:

  • jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
  • jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件
  • 再来加载不带profile:

  • jar包外部的application.properties或application.yml(不带spring.profile)配置文件
  • jar包内部的application.properties或application.yml(不带spring.profile)配置文件
  • @Configuration注解类上的@PropertySource
  • 通过SpringApplication.setDefaultProperties指定的默认属性
  • 自动配置原理

    配置文件可以配置的属性:docs.spring.io/spring-boot…

    自动配置原理:1)Spring Boot启动时加载主配置类(带有@SpringBootApplication),其里面开启了自动配置功能@EnableAutoConfiguration2)@EnableAutoConfiguration利用@Import(AutoConfigurationImportSelector.class)给容器导入一些组件。导入的组件是通过List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取到的。里面通过SpringFactoriesLoader.loadFactoryNames 扫描所有jar包类路径下"META-INF/spring.factories",把扫描到的这些文件的内容包装成properties对象,从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中。其实就是将类路径下 META-INF/spring.factories 里面配置的所有EnableAutoConfiguration的值加入到了容器中。每一个这样的 xxxAutoConfiguration 类都是容器中的一个组件,都加入到容器中;用他们来做自动配置;3)每一个自动配置类进行自动配置功能 4)以HttpEncodingAutoConfiguration配置类进行分析:

    // 表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
    @AutoConfiguration
    // 启动指定类的ConfigurationProperties功能,将配置文件中对应的值和xxxProperties绑定起来,并把xxxProperties加入到ioc容器中
    @EnableConfigurationProperties(ServerProperties.class)
    // Spring底层@Conditional注解(Spring注解版),根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效;
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
    // 判断当前项目有没有这个类CharacterEncodingFilter-SpringMVC中进行乱码解决的过滤器
    @ConditionalOnClass(CharacterEncodingFilter.class)
    // 判断配置文件中是否存在某个配置 spring.servlet.encoding.enabled;如果不存在,判断也是成立的
    // 即使我们配置文件中不配置spring.servlet.encoding.enabled=true,也是默认生效的;
    @ConditionalOnProperty(prefix = "server.servlet.encoding", value = "enabled", matchIfMissing = true)
    public class HttpEncodingAutoConfiguration {
    
        // 他已经和SpringBoot的配置文件映射了
        private final Encoding properties;
    
        // 只有一个有参构造器的情况下,参数的值就会从容器中拿
        public HttpEncodingAutoConfiguration(ServerProperties properties) {
            this.properties = properties.getServlet().getEncoding();
        }
    
        @Bean  // 给容器中添加一个组件,这个组件的某些值需要从properties中获取
        @ConditionalOnMissingBean // 判断容器没有这个组件,就给配置一个
        public CharacterEncodingFilter characterEncodingFilter() {
            CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
            filter.setEncoding(this.properties.getCharset().name());
            filter.setForceRequestEncoding(this.properties.shouldForce(Encoding.Type.REQUEST));
            filter.setForceResponseEncoding(this.properties.shouldForce(Encoding.Type.RESPONSE));
            return filter;
        }
    	...
    }
    

    根据当前不同的条件判断,决定这个配置类是否生效一但这个配置类生效,这个配置类就会给容器中添加各种组件,这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的 5)、所有在配置文件中能配置的属性都是在xxxxProperties类中封装着,配置文件能配置什么就可以参照某个功能对应的这个属性类

    使用精髓: 1)、SpringBoot启动会加载大量的自动配置类 ;2)、我们看我们需要的功能有没有SpringBoot默认写好的自动配置类;3)、我们再来看这个自动配置类中到底配置了哪些组件(只要我们要用的组件有,我们就不需要再来配置了) 4)、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们就可以在配置文件中指定这些属性的值; xxxxAutoConfigurartion:自动配置类; 给容器中添加组件xxxxProperties:封装配置文件中相关属性

    @Conditional注解

    作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效也就是说,自动配置类必须在一定的条件下才能生效

    @Conditional扩展注解 作用(判断是否满足当前指定条件)
    @ConditionalOnJava 系统的java版本是否符合要求
    @ConditionalOnBean 容器中存在指定Bean
    @ConditionalOnMissingBean 容器中不存在指定Bean
    @ConditionalOnExpression 满足SpEL表达式指定
    @ConditionalOnClass 系统中有指定的类
    @ConditionalOnMissingClass 系统中没有指定的类
    @ConditionalOnSingleCandidate 容器中只有一个指定的Bean,或者这个Bean是首选Bean
    @ConditionalOnProperty 系统中指定的属性是否有指定的值
    @ConditionalOnResource 类路径下是否存在指定资源文件
    @ConditionalOnWebApplication 当前是web环境
    @ConditionalOnNotWebApplication 当前不是web环境
    @ConditionalOnJndi JNDI存在指定项

    想要查看生效的自动配置类,可以在配置文件中配置debug=true,positive为启动的,negative没启用的image.png

    Spring Boot与日志

    日志框架

    市场上存在非常多的日志框架:JUL(java.util.logging),JCL(Apache Commons Logging),Log4j,Log4j2,Logback、SLF4j、jboss-logging等。 Spring Boot在框架内容部使用JCL,spring-boot-starter-logging采用了 slf4j+logback的形式,Spring Boot也能自动适配(jul、log4j2、logback) 并简化配置 SpringBoot底层是Spring框架,Spring框架默认是用JCL。SpringBoot选用SLF4j(日志抽象层)和logback(日志实现)

    SLF4j

    开发时日志记录方法的调用,不应该来直接调用日志的实现类,而是调用日志抽象层里面的方法:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    public class HelloWorld {
    
      public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger(HelloWorld.class);
        logger.info("Hello World");
      }
    }
    

    每一个日志的实现框架都有自己的配置文件。使用slf4j以后,配置文件还是做成日志实现框架自己本身的配置文件。如何让系统中所有的日志都统一到slf4j:

  • 将系统中其他日志框架先排除出去
  • 用中间包来替换原有的日志框架
  • 我们导入slf4j其他的实现
  • SpringBoot日志关系

    添加依赖:

    
      org.springframework.boot
      spring-boot-starter-logging
    
    

    image.pngSpringBoot能自动适配所有的日志,而且底层使用slf4j+logback的方式记录日志,引入其他框架的时候,只需要把这个框架依赖的日志框架排除掉即可

    
        org.springframework
        spring‐core
        
            
                commons‐logging
                commons‐logging
            
        
    
    

    默认日志配置

    日志级别由低到高:trace

    
      
        
          %d{yyyy‐MM‐dd HH:mm:ss.SSS} ‐‐‐‐> [%thread] ‐‐‐> %‐5level
            %logger{50} ‐ %msg%n
        
        
          %d{yyyy‐MM‐dd HH:mm:ss.SSS} ==== [%thread] ==== %‐5level
            %logger{50} ‐ %msg%n
        
      
    
    

    Spring Boot与Web开发

    静态资源映射规则

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

    webjars:是以jar包的方式引入静态资源(网址:www.webjars.org/)

    image.png引入后访问:http://localhost:8080/webjars/jquery/3.3.1/src/jquery.js,就可以找到资源:image.png

    2) /** 访问当前项目的任何资源,都去「静态资源的文件夹」找映射

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

    如,localhost:8080/abc,会去静态资源文件夹里面找abcimage.png3)首页映射,静态资源文件夹下的所有index.html页面,被"/**"映射 localhost:8080/ ,会找index页面image.png4)所有的 **/favicon.ico 都是在静态资源文件下找

    Thymeleaf模板引擎

    thymeleaf使用

    默认规则:只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染

    // 源码
    @ConfigurationProperties(prefix="spring.thymeleaf")
    public class ThymeleafProperties{
    
    	private static final Charset DEFAULT_ENCODING = Charset.forName("UTF‐8");
    	private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
    	public static final String DEFAULT_PREFIX = "classpath:/templates/";
    	public static final String DEFAULT_SUFFIX = ".html";
    

    第一步)添加依赖

     
          org.springframework.boot
          spring-boot-starter-thymeleaf
      
    

    第二步)属性配置

    # 将缓存关闭
    spring.thymeleaf.cache=false
    

    第三步)创建thymeleaf模板文件创建success.html,放入classpath:/templates/文件夹下

    
    
    
    
        
        Title
    
    
        成功页面!
    		
        
    
    
    

    第四步)编写控制器

    // 这里需要使用@Controller,而不是@RestController
    @Controller
    @RequestMapping("/api")
    public class Hello {
        @ResponseBody
        @RequestMapping("/hello")
        public String hello() {
            return "hello";
        }
    
        @RequestMapping("/success")
        public String success(Model model) {
            // classpath:/templates/success.html
            model.addAttribute("name","alice");
            return "success";
        }
    }
    

    第五步)访问页面访问http://localhost:8080/api/success,可以看到html页面内容

    thymeleaf语法规则

    1)th:text:改变当前元素里面的文本内容(th:任意html属性:来替换原生属性的值)image.png2)表达式

    【 Simpleexpressions:(表达式语法) 】
        1、Variable Expressions: ${...}:获取变量值(OGNL)
            1)、获取对象的属性、调用方法
            2)、使用内置的基本对象:
                #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.
                #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{...} syntax.
                #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.
                #ids : methods for dealing with id attributes that might be repeated (for example, as aresult of an iteration).
    
            2、Selection Variable Expressions: *{...}:选择表达式。和${}在功能上是一样(补充:配合th:object="${session.user})
           	例子:
            
                

    Name: Sebastian.

    Surname: Pepper.

    Nationality: Saturn.

    3、Message Expressions: #{...}:获取国际化内容 4、Link URL Expressions: @{...}:定义URL; 例子:@{/order/process(execId=${execId},execType='FAST')} 5、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): ‐ 【Booleanoperations:(布尔运算)】 Binary operators: and , or Boolean negation (unary operator): ! , not 【Comparisonsandequality:(比较运算)】 Comparators: > , = , 运行镜像-->产生一个容器(正在运行的软件,运行的QQ)

    操作命令说明
    运行docker run --name container-name -d image-nameeg:docker run –name myredis –d redis-name:自定义容器名-d:后台运行image-name:指定镜像模板
    列表docker ps(查看运行中的容器)加上-a可以查看所有容器
    停止docker stop container-name/container-id停止当前运行的容器
    启动docker start container-name/container-id启动容器
    删除docker rm container-id删除指定容器
    端口映射-p 6379:6379eg:docker run -d -p 6379:6379 --name myredis docker.io/redis-p: 主机端口(映射到)容器内部的端口‐d:后台运行
    容器日志docker logs container-name/container-id

    更多命令可查看:docs.docker.com/engine/refe…

    示例(tomcat):

    % docker images //查看镜像列表
    % docker search tomcat //搜索镜像
    % docker pull tomcat //拉取镜像
    % docker run --name myTomcat -d tomcat:latest //根据镜像启动容器
    % docker ps //查看运行中的容器
        ------输出------
        CONTAINER ID   IMAGE           COMMAND             CREATED          STATUS          PORTS      NAMES
        700a4fa11db6   tomcat:latest   "catalina.sh run"   25 seconds ago   Up 24 seconds   8080/tcp   myTomcat
    % docker stop 700a4fa11db6[容器ID] //停止运行中的容器
    % docker ps -a //查看所有的容器
        ------输出------
        CONTAINER ID   IMAGE           COMMAND             CREATED         STATUS                            PORTS     NAMES
        700a4fa11db6   tomcat:latest   "catalina.sh run"   5 minutes ago   Exited (143) About a minute ago             myTomcat
    % docker start 700a4fa11db6[容器ID] //启动容器
    % docker rm 700a4fa11db6[容器ID] //删除一个容器
    % docker run -d -p 8888:8080 tomcat //启动一个做了端口映射的tomcat
        ‐d:后台运行
        ‐p: 将主机的端口映射到容器的一个端口 主机端口:容器内部的端口
        ------docker ps 输出------
        CONTAINER ID   IMAGE     COMMAND             CREATED          STATUS          PORTS                    NAMES
    	8dbc9df132b4   tomcat    "catalina.sh run"   19 seconds ago   Up 19 seconds   0.0.0.0:8888->8080/tcp   eloquent_moore
    % dockerlogscontainer‐name/container‐id //查看容器的日志
    

    示例(mysql):

    % docker pull mysql
    % docker run --name mysql01 -e MYSQL_ROOT_PASSWORD=123456 -d mysql //启动mysql
        ------输出------
    	c9c10a720ba86f440737503396019c80ad0de88b8ae659e19214d8eda3253481
    
    
    几个其他的高级操作:
        
    docker run --name mysql03 ‐v /conf/mysql:/etc/mysql/conf.d ‐e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag
    把主机的/conf/mysql文件夹挂载到mysql docker容器的/etc/mysql/conf.d文件夹里面
    改mysql的配置文件就只需要把mysql配置文件放在自定义的文件夹下(/conf/mysql)
    
    docker run --name some‐mysql ‐e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag --character‐set‐server=utf8mb4 ‐‐collation‐server=utf8mb4 --collation -server=utf8mb4_unicode_ci
    指定mysql的一些配置参数
    

    Spring Boot与数据访问

    对于数据访问层,无论是SQL还是NOSQL,Spring Boot默认采用整合Spring Data的方式进行统一处理,添加大量自动配置,屏蔽了很多设置。引入各种xxxTemplate、xxxRepository来简化我们对数据访问层的操作。对我们来说只需要进行简单的设置即可。JDBC、MyBatis、JPA

    整合JDBC 🔥

    image.png配置:

    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/jdbc
    spring.datasource.username=root
    spring.datasource.password=root
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    

    测试代码:

    @SpringBootTest
    class SpringDemo08JdbcApplicationTests {
        @Autowired
        DataSource dataSource;
    
        @Test
        void contextLoads() {
            // 默认使用的是 class com.zaxxer.hikari.HikariDataSource 数据源
            System.out.println(dataSource.getClass());
        }
    }
    

    数据源的相关配置都在DataSourceProperties源代码里面

    // 源码
    @ConfigurationProperties(
        prefix = "spring.datasource"
    )
    

    SpringBoot默认可以支持:org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource、自定义数据源类型。

    验证JDBC

    配置文件里增加如下配置:

    #spring.datasource.initialization-mode=always  此行已失效,使用下面的
    spring.sql.init.mode=always
    

    编写SQL并放在resources文件夹下面image.png启动springboot工程,刷新数据库,可以看到表成功创建(下次启动还是会创建,所以最好创建完毕后删除sql文件)
    image.png编写测试查询代码

    @SpringBootTest
    class SpringDemo08JdbcApplicationTests {
    
        @Autowired
        JdbcTemplate jdbcTemplate;
    
        @Test
        void contextLoads() {
            List list = jdbcTemplate.queryForList("select * from Skynet_test");
            System.out.println(list);
            // [{id=46, date=2023-06-01, APPversion=1.2.3, uv=123456, tag=gray, platform=Android, 
            // create_time=2023-06-01, last_modify=2023-06-01, version=1.2}]
        }
    }
    

    整合Druid数据源

    引入依赖

    
    
      com.alibaba
      druid
      1.1.8
    
    

    修改配置文件

    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/jdbc
    spring.datasource.username=root
    spring.datasource.password=root1234
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource // 切换数据源
    

    测试代码

    @Test
    void contextLoads() {
        System.out.println(dataSource.getClass()); // class com.alibaba.druid.pool.DruidDataSource
    }
    

    配置生效:

    @Configuration
    public class DruidConfig {
        @ConfigurationProperties(prefix = "spring.datasource")
        @Bean
        public DataSource druid(){
            return new DruidDataSource();
        }
        // 这样在配置文件中配置druid的一些属性就可以生效了
    }
    

    整合Mybatis 🔥

    image.png

    验证Mybatis

    引入上方的druid数据源配置文件:

    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/jdbc
    spring.datasource.username=root
    spring.datasource.password=root1234
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    

    建表语句:

    CREATE TABLE `department` (
      `id` int NOT NULL AUTO_INCREMENT,
      `departmentName` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
    
    CREATE TABLE `employee` (
      `id` int NOT NULL AUTO_INCREMENT,
      `lastName` varchar(255) DEFAULT NULL,
      `email` varchar(255) DEFAULT NULL,
      `gender` int DEFAULT NULL,
      `d_id` int DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
    

    创建JavaBean:Employee & Department

    注解版

    @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);
    }
    

    测试验证:

    @RestController
    public class DepartmentController {
        @Autowired
        DepartmentMapper departmentMapper;
    
        @GetMapping("/dept/{id}")
        public Department getDepartment(@PathVariable("id") Integer id) {
            return departmentMapper.getDeptById(id);
            // 测试链接:http://localhost:8080/dept/1
            // 返回:{"id":1,"departmentName":"开发部"}
        }
    
        @GetMapping("/dept")
        public Department insertDepartment(Department department) {
            departmentMapper.insertDept(department);
            return department;
            // 测试链接:http://localhost:8080/dept?departmentName=开发部
            // 返回:{"id":1,"departmentName":"开发部"}
        }
    }
    

    如果此时数据库里字段是(department_name),查询结果就展示不出来名字了:{"id":1,"departmentName":null}。如何开启驼峰命名法配置?方法是自定义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); // 开启驼峰命名
                }
            };
        }
    }
    

    另一个问题是,每个mapper上都需要标注@Mapper注解,自动扫描配置呢?

    @MapperScan(value = "com.example.spring_demo09_mybatis.mapper") // 批量扫描所有的Mapper接口
    @SpringBootApplication
    public class SpringDemo09MybatisApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringDemo09MybatisApplication.class, args);
        }
    
    }
    

    配置文件版

    @Mapper
    public interface EmployeeMapper {
        public Employee getEmpById(Integer id);
        public void insertEmp(Employee employee);
    }
    

    mybatis配置文件:

    
    
    
    
        
            
        
    
    
    
    
    
       
        
            SELECT * FROM employee WHERE id=#{id}
        
    
        
        
            INSERT INTO employee(lastName,email,gender,d_id) VALUES (#{lastName},#{email},#{gender},#{dId})
        
    
    

    image.png修改Spring配置文件增加如下内容:

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

    测试方法:

    @GetMapping("/emp/{id}")
    public Employee getEmp(@PathVariable("id") Integer id) {
        return employeeMapper.getEmpById(id);
        // 测试链接:http://localhost:8080/emp/1
        // 返回:{"id":1,"lastName":"Wang","gender":1,"email":"1111@qq.com","dId":1}
    }
    

    使用参考:mybatis.org/spring-boot…

    整合JPA

    Spring Data 项目的目的是为了简化构建基于 Spring 框架应用的数据访问技术,包括非关系数据库、 Map-Reduce 框架、云数据服务等等,另外也包含对关系数据库的访问支持。SpringData 为我们提供使用统一的API来对数据访问层进行操作,这主要是Spring Data Commons项目来实现的。Spring Data Commons让我们在使用关系型或者非关系型数据访问技术时都基于Spring提供的统一标准,标准包含了CRUD(创建、获取、更新、删除)、查询、 排序和分页的相关操作。image.png统一的Repository接口:

    • Repository:统一接口
    • RevisionRepository:基于乐观锁机制
    • CrudRepository:基本CRUD操作
    • PagingAndSortingRepository:基本CRUD及分页

    提供数据访问模板类 xxxTemplate,如:MongoTemplate、RedisTemplate等

    验证JPA

    image.png1)、编写一个bean实体类和数据表进行映射,并且配置好映射关系;

    package com.example.spring_demo10_jpa.entity;
    
    import javax.persistence.*;
    
    // 使用JPA注解配置映射关系
    @Entity //告诉JPA这是一个实体类(和数据表映射的类)
    @Table(name = "tbl_user") // @Table来指定和哪个数据表对应,如果省略默认表名就是user
    public class User {
        @Id // 代表这是一个主键
        @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增主键
        private Integer id;
    
        @Column(name = "name", length = 50) // 这是和数据表对应的一个列
        private String name;
    
        @Column // 省略默认列名就是属性名
        private String email;
    }
    

    2)、编写一个Dao接口来操作实体类对应的数据表(Repository)

    // 继承JpaRepository来完成对数据库的操作
    public interface UserRepository extends JpaRepository {
    }
    

    3)、基本的配置

    #jpa
    #更新或者创建数据表结构
    spring.jpa.hibernate.ddl-auto=update
    #控制台新鲜事SQL
    spring.jpa.show-sql=true
    

    4)、启动工程,自动生成数据表:image.png5)、测试

    @RestController
    public class UserController {
        @Autowired
        UserRepository userRepository;
    
        //    @GetMapping("/user/{id}")
        //    public User getUser(@PathVariable("id") Integer id){
        //        User user = userRepository.findOne(id);
        //        return user;
        //    }
    
        @GetMapping("/user")
        public User insertUser(User user){
            User save = userRepository.save(user);
            return save;
        }
    }
    

    请求http://localhost:8080/user?name=haha&email=qqqq@qq.com会进行日志输出:Hibernate: insert into tbl_user (email, name) values (?, ?)

    Spring Boot启动配置原理

    启动流程

    SpringApplication.run(主程序类)1、 创建SpringApplication对象;这一步主要是加载并保存所有的 ApplicationContextInitializer 和 ApplicationListener,并获取到主程序类2、运行run()方法;回调所有的SpringApplicationRunListener的starting、准备环境、创建ioc容器对象(web环境容器和普通环境容器)

    事件监听机制

    1、准备环境

    • 执行ApplicationContextInitializer. initialize()
    • 监听器SpringApplicationRunListener回调contextPrepared
    • 加载主配置类定义信息
    • 监听器SpringApplicationRunListener回调contextLoaded

    2、刷新启动IOC容器

    • 扫描加载所有容器中的组件
    • 包括从META-INF/spring.factories中获取的所有EnableAutoConfiguration组件

    3、回调容器中所有的ApplicationRunner、CommandLineRunner的run方法

    4、监听器SpringApplicationRunListener回调finished

    Spring Boot自定义starters

    编写自动配置:

    @Configuration //指定这个类是一个配置类
    @ConditionalOnXXX //在指定条件成立的情况下自动配置类生效
    @AutoConfigureAfter //指定自动配置类的顺序
    @Bean //给容器中添加组件
    
    @ConfigurationPropertie结合相关xxxProperties类来绑定相关的配置
    @EnableConfigurationProperties//让xxxProperties生效加入到容器中
    
    自动配置类要能加载,将需要启动就加载的自动配置类,配置在META‐INF/spring.factories
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=
    org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,
    org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,
    

    设计模式:启动器starter只用来做依赖导入;专门写一个自动配置模块,启动器依赖这个自动配置模块;自定义启动器名-spring-boot-starter

    相关文章

    JavaScript2024新功能:Object.groupBy、正则表达式v标志
    PHP trim 函数对多字节字符的使用和限制
    新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
    使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
    为React 19做准备:WordPress 6.6用户指南
    如何删除WordPress中的所有评论

    发布评论