Spring Boot学习笔记

1、微服务阶段

javase: OOP

mysql: 持久化

前端:html+css+js+jquery+框架

java web

ssm:框架:简化了开发流程,配置也开始较为复杂

war包

spring再简化: Spirng Boot-jar包: 微服务架构

服务越来越多:spring cloud

2、第一个Spring Boot程序

环境:

  • jdk 1.8
  • maven 3.6.1
  • Spring Boot
  • IDEA

官方:提供了一个快速生成的网站!IDEA集成了这个网站。

  • 可以在官网下载后,导入IDEA开发
  • 直接使用IDEA创建一个Spring Boot项目

3、自动装配原理

pom.xml

  • spring-boot-dependencies: 核心依赖在父工程中!
  • spring-boot-starter: 已经配置资源过滤
  • 我们在写或者引入一些Spring Boot依赖的时候,不需要指定版本,就因为有这些版本仓库

启动器

  • <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    
  • 启动器: 说白了就是Spring Boot的启动场景

  • 比如spring-boot-starter-web, 它就会帮我们自动导入web环境所有的依赖!

  • spring boot会将所有的功能场景, 都变成一个个的启动器

  • 我们要使用什么功能, 就只需要找到对应的启动器就可以了, starter

主程序

@SpringBootApplication
public class Springboot01HelloworldApplication {
    public static void main(String[] args) {
      SpringApplication.run(Springboot01HelloworldApplication.class, args);
    }
}
  • 注解

    • @SpringBootConfiguration: springboot的配置
      	@Configuration: spring配置类
          @Component: 说明这也是一个Spring的组件
      @EnableAutoConfiguration: 自动配置
      	@AutoConfigurationPackage: 自动配置包
          @Import(AutoConfigurationPackages.Registrar.class): 自动配置`包注册`
          @Import(AutoConfigurationImportSelector.class): 自动导入选择
          // 获取所有的配置
          List<String> configurations = getCandidateConfigurations(annotationMetadata,attributes)
      

      获取候选的配置

      protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
          List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
                                                                               getBeanClassLoader());
          Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
                          + "are using a custom packaging, make sure that file is correct.");
          return configurations;
      }
      

      META-INF/spring.factories: 自动配置的核心文件

结论: Spring Boot所有自动配置都是在启动的时候扫描并加载: spring.factories所有的自动配置类都在这里面, 但是不一定生效, 要判断条件是否成立, 只要导入了对应的start, 就有对应的启动器了, 有了启动器, 我们的自动配置就会生效, 然后就配置成功!

  1. Spring Boot 在启动的时候, 从类路径下 /META-INF/spring.factories获取指定的值
  2. 将这些自动配置的类导入容器, 自动配置就会生效, 帮我进行自动配置
  3. 以前我们需要自动配置的东西, 现在Spring Boot帮我们做了
  4. 整合javaEE, 解决方案和自动配置的东西都在spring-boot-autoconfigure-2.2.0.RELEASE.jar这个包下
  5. 它会把所有需要导入的组件, 以类名的方式返回, 这些组件就会被添加到容器
  6. 容器中也会存在非常多的xxxAutoConfiguration的文件(@Bean), 就是这些类给容器中导入了这个场景需要的所有组件, 并自动配置, @Configuration, JavaConfig!
  7. 有了自动配置类, 免去了手动编写配置文件的工作!
  • SpringApplication

    这个类主要做了以下四件事情

    1. 推断应用的类是普通的项目还是Web项目
    2. 查找并加载所有可用初始化器, 设置到initializers属性中
    3. 找出所有的应用程序监听器, 设置到listeners属性中
    4. 推断并设置main方法的定义类, 找到运行的主类

关于Spring Boot, 谈谈你的理解:

  • 自动装配
  • run()

全面接管Spring MVC的配置

4、yaml语法

Spring Boot使用一个全局的配置文件, 配置文件名称是固定的

  • application.properties
    • key = value
  • application.yaml
    • key: value (冒号后面有空格)
server:
  port: 8081
# 对象
student:
  name: tangyixing
  age: 23
# 行内写法
student: {name: tangyixing, age: 23}
# 数组
pets:
  - cat
  - dog
  - pig
pets: [cat, dog, pig]

yaml可以直接给实体类赋值

  1. Spring给实体类赋值

    @Component
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Dog {
        @Value("旺柴")
        private String name;
        @Value("3")
        private Integer age;
    }
    
  2. 使用yaml给实体类赋值

    application.yaml

    person:
      name: tangyixing${random.uuid}
      age: ${random.int}
      happy: false
      birth: 1998/08/24
      maps: {k1: v1, k2: v2}
      lists:
        - code
        - music
        - girl
      dog:
        name: ${person.hello:hello}旺柴
        age: 3
    

    Person.java

    @Component
    @ConfigurationProperties(prefix = "person")
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    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;
    }
    

    报红可添加依赖

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

松散绑定:yaml中用first-name,实体类中用firstName

结论:

  • 配置yaml和properties都可以获取到值,强烈推荐yaml
  • 如果我们在某个业务中,只需要获取配置文件中的某个值,可以使用一下@value
  • 如果说,我们专门编写了一个JavaBean来和配置文件进行映射,就直接使用@configurationProperties,不要犹豫!

5、JSR303校验

添加pom依赖

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

Person.java

@Component
@ConfigurationProperties(prefix = "person")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Validated
public class Person {
    @Email(message = "请输入正确的电子邮箱格式")
    private String name;
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;
}

6、多环境配置及配置文件位置

application.yaml可以放在:

  1. file: ./config/
  2. file: ./
  3. classpath: /config/
  4. classpath: /

备注: file是指项目的根目录, classpath是指resources目录

优先级: file: ./config > file: ./ > classpath: /config/ > classpath: /

多环境配置

写在不同文件里

  • application.yaml
  • application-test.yaml
  • application-dev.yaml

application.yaml

spring:
  profiles:
    active: dev

写在一个文件里

application.yaml

server:
  port: 8081

spring:
  profiles:
    active: test
---
server:
  port: 8082
spring:
  profiles: dev
---
server:
  port: 8083
spring:
  profiles: test

7、自动装配原理再理解

  1. Spring Boot 启动会加载大量的自动配置类
  2. 我们看我们需要的功能有没有在Spring Boot默认写好的自动配置类当中
  3. 我们再来看这个自动配置类中到底配置了哪些组件(只要我们要用的组件存在其中,我们就不需要再手动配置了)
  4. 给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们只需要在配置文件中指定这些属性的值即可

xxxAutoConfiguration:自动配置类,给容器中添加组件

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

8、Spring Boot Web开发

要解决的问题:

  • 导入静态资源:HTML,CSS,JavaScript
  • 首页
  • jsp,模板引擎Thymeleaf
  • 装配扩展Spring MVC
  • 拦截器
  • 国际化

9、静态资源导入

webjars:以maven方式导入jquery等静态资源

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

http://localhost:8080/webjars/jquery/3.5.1/jquery.js

在resources目录下的

  • public(公共资源)
  • static(图片)
  • resources(上传的文件)

静态资源都可以被直接访问到

优先级: resources > static > public

总结:

  1. 在spring boot中,我们可以使用以下方式处理静态资源
    • webjars 映射到 localhost:8080/webjars/…
    • public, static, /**, resources 映射到 localhost:8080/
  2. 优先级: resources > static(默认) > public

10、首页及图标定制

首页

首页:index.html

在templates目录下的,只能通过controller来跳转,相当于原来的WEB-INF目录

图标

将favicon.ico放到classpath: static

<link rel="icon" href="favicon.ico">

11、Thymeleaf模板引擎

导入pom依赖

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

结论:只要需要使用Thymeleaf,只需要导入对应的依赖就可以了!我们将HTML页面放在我们的templates目录下即可。

public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";

Controller

@GetMapping("test")
public String test(Model model) {
    model.addAttribute("msg", "hello,springboot");
    return "test";
}

test.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${msg}"></h1>
</body>
</html>

转义:显示效果

@GetMapping("test")
public String test(Model model) {
    model.addAttribute("msg", "<h1>hello,springboot</h1>");
    return "test";
}
<h1 th:utext="${msg}"></h1>

遍历列表

model.addAttribute("users", Arrays.asList("tangyixing", "Eimhin"));
<h3 th:each="user:${users}" th:text="${user}"></h3>
<h3 th:each="user:${users}">[[${user}]]</h3>

12、扩展装配Spring MVC

MyMvcConfig.java

// 如果想diy一些定制化的功能, 只要写这个组件, 然后将它交给Spring Boot, Spring Boot就会帮我们自动装配.
// 扩展Spring MVC  dispatchServlet
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

    }

    @Bean
    public ViewResolver myViewResolver() {
        return new MyViewResolver();
    }

    public static class MyViewResolver implements ViewResolver {
        @Override
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;
        }
    }
}
// 如果我们要扩展Spring MVC, 官方建议我们这样去做.
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    // 视图跳转
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/tangyixing").setViewName("wechat");
    }
}

13、员工管理系统

13.1 首页配置

13.2 页面国际化

  1. 配置i18n文件

  2. 如果需要用按钮进行自动切换,需要自定义一个组件LocaleResolver

    MyLocaleResolver.java

    public class MyLocaleResolver implements LocaleResolver {
        @Override
        public Locale resolveLocale(HttpServletRequest httpServletRequest) {
            String language = httpServletRequest.getParameter("l");
            System.out.println(language);
            Locale locale = Locale.getDefault();
            if (!StringUtils.isEmpty(language)) {
                String[] split = language.split("_");
                locale = new Locale(split[0], split[1]);
            }
            return locale;
        }
    
        @Override
        public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
    
        }
    }
    
  3. 记得将自己写的组件配置到Spring容器@Bean

    MyMvcConfig.java

    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index");
            registry.addViewController("/index.html").setViewName("index");
        }
    
        @Bean
        public LocaleResolver localeResolver() {
            return new MyLocaleResolver();
        }
    }
    
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值