SpringBoot2笔记

1、入门体验

1.1、系统要求
  • Java 8+
  • Maven 3.3+
1.2、Maven设置
//阿里云镜像
  
      
        nexus-aliyun
        central
        Nexus aliyun
        http://maven.aliyun.com/nexus/content/groups/public
      
  
 
  
         
              jdk-1.8
              
                true
                1.8
              
              
                1.8
                1.8
                1.8
              
         
  
1.3、HelloWorld
  • 创建Maven工程
  • pom.xml引入依赖
    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.4.RELEASE
         
    

    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
   
    
    
        
            
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    
  • 创建主程序(应用执行入口)
//注解说明这是一个springboot应用
@SpringBootApplication
public class MyBootApplication {

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

}
  • 创建业务程序
@Controller
public class HelloWorld {

    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello SpringBoot";
    }
}
  • 运行主程序中的main方法,启动应用
  • 使用浏览器访问地址测试
  • resources目录下创建application.properties文件,可集中管理springboot中的各种配置信息

2、自动配置

2.1、依赖管理
  • 父项目版本锁定

    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.4.RELEASE
         
    

  
    org.springframework.boot
    spring-boot-dependencies
    2.3.4.RELEASE
  

  
    5.15.13
    2.7.7
    1.9.82
    2.12.0
    1.9.6
    3.16.1
    4.0.6
    4.0.3
    2.1.4
    3.1.0
    1.10.14
    2.8.5
    4.6.1
    1.5.1
    1.14
    2.7.0
    ......
  • 导入starter场景
    1、springboot提供了非常多的开发场景
    https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter
    2、导入场景后,所有常规依赖都将被引入

        
            org.springframework.boot
            spring-boot-starter-web
        
  • 修改默认依赖版本
    1、找到父项目中版本锁定的参数名称
    2、根据Maven就近原则更改依赖版本
    
        8.0.21
    
2.2、自动配置
  • 根据导入的场景选择配置相应的功能
  • 各项配置都拥有默认值

3、容器

3.1、组件添加
  • @Configuration
    1、@Configuration注解可以声明配置类,用于添加一个或多个使用@Bean标记的方法,该类方法用于生成Bean实例,并且交由Spring管理
    2、@Configuration包含proxyBeanMethods属性,表示使用@Bean标记的方法是否使用代理,默认为true,代表将从IOC容器中直接获取实例;如果设置为false,则表示每次调用@Bean标记的方法获取的对象,都是重新创建的;
@Configuration
public class MyConfiguration {

    @Bean
    public User myUser() {
        User user = new User(10001, "张三");
        return user;
    }

}
  • @Component、@Service、@Controller、@Repository
  • @ComponentScan
    1、SpringBoot默认扫描主程序所在路径及子路径下的所有目录,并加载允许被扫描的组件
    2、使用@ComponentScan可以指定扫描路径
//主程序在com.study.boot2包下,默认扫描该包及其子目录
//使用@ComponentScan可以将指定扫描路径
@Configuration
@ComponentScan(basePackages = "com.study")
public class MyConfiguration {

}
  • @Import
    1、可以直接将类实例导入并交由Spring管理
    2、导入的类可以不需要标记@Component注解,即使与主程序不同包或子路径
@Configuration
@Import(value = {User.class, Animal.class})
public class MyConfiguration {
}
  • @Conditional、@ConditionalOnXxx
    1、根据条件进行添加
    2、@Conditional配合Condition接口实现类使用
    3、SpringBoot内置了@ConditionalOnBean、@ConditionalOnMissingBean、@ConditionalOnClass等等

  • @ImportResource引入原生配置文件
    1、resources目录下创建xml配置文件
    2、使用@ImportResource("classpath:beans.xml")引入Bean实例

3.2、配置绑定
  • 只有在Spring注册的组件才能使用配置属性功能
  • 使用@Component注册组件后可使用
@Component
@ConfigurationProperties(prefix = "user")
public class User {
    private int id;
    private String username;
//application.properties
user.id=10000
user.username=zhansan
  • @EnableConfigurationProperties开启配置属性功能,并注册组件
@ConfigurationProperties(prefix = "user")
public class User {
    private int id;
    private String username;
@Configuration
@EnableConfigurationProperties({User.class})
//@Import(value = {User.class, Animal.class})
public class MyConfiguration {

4、核心功能

1、配置文件

1.1、properties文件
1.2、yaml

YAML 是 "YAML Ain't a Markup Language"(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言)。
YAML 的语法和其他高级语言类似,并且可以简单表达清单、散列表,标量等数据形态。它使用空白符号缩进和大量依赖外观的特色,特别适合用来表达或编辑数据结构、各种配置文件、倾印调试内容、文件大纲(例如:许多电子邮件标题格式和YAML非常接近)。
YAML 的配置文件后缀为 .yml,如:runoob.yml 。

1.2.1、基本语法

  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进不允许使用tab,需使用空格,Idea已自动优化
  • 相同层级的元素需要左对齐
  • #代表注释
  • 字符串无需加引号,单引号会转义特殊字符

1.2.2、配置提示

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

1.2.3、数据类型

#纯量(字符串、布尔值、整数、浮点数、Null、时间、日期)
#冒号:后面有一个空格
k: v

#对象、结合
k: {k1:v1,k2:v2,k3:v3}
k:
  k1: v1
  k2: v2
  k3: v3

#数组
k: [v1,v2,v3]
k:
  - v1
  - v2
  - v3

菜鸟教程:https://www.runoob.com/w3cnote/yaml-intro.html](https://www.runoob.com/w3cnote/yaml-intro.html

2、Web开发

2.1、静态资源
  • 静态资源默认目录
    resources目录下static、public、resources、META-INF/resources,可使用项目根路径/ + 静态资源名直接访问
    请求流程是先交给Controller处理,不存在则交给静态资源处理器处理,找不到则响应404
  • 改变默认的静态资源路径
#application.yml
spring:
  resources:
    static-locations:[classpath:/mysource]
  • 改变静态资源访问前缀
spring:
  resources:
    static-locations: [classpath:/mysource]
  mvc:
    static-path-pattern: /mystatic/**

静态资源访问:http://localhost:8080/mystatic/cafe.jpg

2.2、欢迎页、favicon
  • 静态资源路径下index.html可默认加载
  • 静态资源路径下favicon.ico自动加载
  • 自定义静态资源访问前缀spring.mvc.static-path-pattern配置后,将影响上述功能
2.3、请求参数
1、rest风格
  • 以Http请求类型的不同来区分对数据的操作
  • GET:获取数据;POST:保存数据;PUT:修改数据;DELETE:删除数据
  • Form表单使用rest风格,请求方式必须为post,且携带隐藏域“_method”来标注请求类型
  • 其他客户端则可以直接发送相应类型的请求
  • form表单使用resit风格需要在springboot配置中手动开启
spring:
  mvc:
    hiddenmethod:
      filter:
        enabled: true   #开启页面表单的Rest功能
2、获取参数注解
  • @PathVariable
    1、将URL规则中的占位符绑定到方法形参中
    2、使用Map可接收全部参数
    @GetMapping("/param/{id}/{name}")
    public Map paramController(@PathVariable("id") Integer id,
                                               @PathVariable("name") String name,
                                               @PathVariable Map pv) {

  • @RequestParam
    1、直接将请求URL中的参数绑定到方法形参中
    2、使用Map可以接收全部参数
    //URL:http://localhost:8080/show?id=101&hobby=吃饭&hobby=睡觉
    @GetMapping("/show")
    public Map paramController(@RequestParam("id") Integer id,
                                               @RequestParam("hobby") List hobbies,
                                               @RequestParam Map params) {

  • @RequestHeader
    1、将请求头信息绑定到方法形参中
    2、使用Map可以获取全部
    @GetMapping("/show")
    public Map paramController(@RequestHeader("User-Agent") String userAgent,
                                               @RequestHeader Map header) {

  • @CookieValue
    1、获取请求携带的Cookie值
    2、通过Cookie类型的参数可获得某条Cookie的对象信息
    @GetMapping("/show")
    public Map paramController(@CookieValue("JSESSIONID") String jsessionid,
                                               @CookieValue("JSESSIONID") Cookie cookie) {

        HashMap map = new HashMap<>();
        map.put("value", jsessionid);
        map.put("name", cookie.getName());

        return map;
    }
//打印结果
{
    "name": "JSESSIONID",
    "value": "fsdfsdf"
}
  • @RequestBody
    1、常用来处理客户端传递的json数据
    2、请求类型必须为POST或PUT
    3、可以将请求信息数据直接封装为实体类对象

  • @MatrixVariable

1、开启矩阵参数功能

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

2、单个值演示

    //请求路径:http://localhost:8080/cars/22;color=green
    @GetMapping("/cars/{id}")
    public String showData(@PathVariable Integer id,
                           @MatrixVariable String color)
    {

        System.out.println(id); //id=22
        System.out.println(color); //color=green
    //请求路径:http://localhost:8080/cars/color=green
    @GetMapping("/cars/{path}")
    public String showData(@PathVariable String path,
                           @MatrixVariable String color)
    {
        System.out.println(path); //输出  color=green
        System.out.println(color); //输出  green

3、多个值演示

    //请求路径:http://localhost:8080/cars/3008;color=green,white,yellow
    @GetMapping("/cars/{id}")
    public String showData(@PathVariable Integer id,
                           @MatrixVariable List color)
    {
        System.out.println(id); //输出  3008
        System.out.println(color); //输出  [green, white, yellow]

4、多单元重名

    //请求路径:http://localhost:8080/cars/3008;color=green,white,yellow/4008;color=black,red
    @GetMapping("/cars/{type1}/{type2}")
    public String showData(@PathVariable Integer type1,
                           @MatrixVariable(name = "color", pathVar = "type1") List color1,
                           @PathVariable Integer type2,
                           @MatrixVariable(name = "color", pathVar = "type2") List color2)
    {
        System.out.println(type1); //输出  3008
        System.out.println(type2); //输出  4008
        System.out.println(color1); //输出  [green, white, yellow]
        System.out.println(color2); //输出  [black, red]

3、数据访问

3.1、SQL
1、导入场景
  • SpringBoot2.3.4默认引入8.*的mysql,请选择对应版本
        5.1.49

        
            org.springframework.boot
            spring-boot-starter-data-jdbc
        
        
            mysql
            mysql-connector-java
        
2、数据源配置项
  • 数据源自动装配参数在自动装配包下jdbc/DataSourceProperties.class中
spring:
  resources:
    static-locations: [classpath:/mysource]
  mvc:
    static-path-pattern: /mystatic/**
  datasource:
    url: jdbc:mysql://localhost:3306/java_test1
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
3.2、配置Druid数据源
  • Druid官方配置说明
    https://github.com/alibaba/druid](https://github.com/alibaba/druid

  • 导入Druid场景

spring:
  resources:
    static-locations: [classpath:/mysource]
  mvc:
    static-path-pattern: /mystatic/**
  datasource:
    url: jdbc:mysql://localhost:3306/java_test1?useSSL=false
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

    #配置druid数据源扩展参数
    druid:
      #监控页功能
      stat-view-servlet:
        enabled: true #功能开启
        login-password: 123456
        login-username: admin
        reset-enable: true
      #Web关联状态监控
      web-stat-filter:
        enabled: true
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
      #添加要使用的过滤器
      filters: stat,wall
      #配置过滤器
      filter:
        #sql统计
        stat:
          enabled: true
          slow-sql-millis: 1000
          log-slow-sql: true
        #防火墙
        wall:
          enabled: true
      #Spring关联状态监控
      aop-patterns: com.study.springboot2
  • Druid内置监控页默认地址
    http://localhost:8080/druid/index.html
3.3、MyBatis-Plus
1、导入场景
  • MyBatis-Plus官网
    https://baomidou.com
  • pom文件引入依赖

    com.baomidou
    mybatis-plus
    3.4.2

  • MyBatis-Plus已包含JDBC和MyBatis依赖,无需再次导入
2、mapper文件
  • MyBatis-Plus提供了Mapper CRUD接口,只需继承BaseMapper接口
  • 使用@Mapper注解标注映射文件
@Mapper
public interface UserMapper extends BaseMapper {
}
  • 复杂的Sql操作可配置xml文件
  • mapper.xml文件默认放在类路径下mapper文件夹下,MyBatis-Plus默认加载xml文件路径是:"classpath*:/mapper/**/*.xml"
3、service文件
  • MyBatis-Plus提供了Service CRUD接口
  • 自定义接口继承IService接口
public interface UserService extends IService {
}
  • 自定义实现类继承ServiceImpl并实现UserService接口
@Service
public class UserServiceImpl extends ServiceImpl implements UserService {
}
  • Controller文件中可直接使用Service封装的CRUD方法
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/userList")
    public List userList() {
        List list = userService.list();
        return list;
    }

    @GetMapping("/getUser")
    public User getUser(@RequestParam("id") int id) {
        User user = userService.getById(id);
        return user;
    }
}

你可能感兴趣的:(SpringBoot2笔记)