SpringBoot learning (unfinished)

SpringBoot learning

Getting started

Run SpringBoot quickly

Import the corresponding dependencies in pom.xml

    <!--导入springboot-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.0</version>
    </parent>

    <dependencies>
        <!--导入web开发场景-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

Create a main function of springboot

package com.xzh.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/6/7 12:03
 * @SpringBootApplication 生命这是一个springboot应用
 */
@SpringBootApplication
public class MainApplicationContext {
    public static void main(String[] args) {
        SpringApplication.run(MainApplicationContext.class,args);
    }
}

Create a control layer

package com.xzh.boot.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/6/7 12:05
 */
//这个注解是ResponseBody和Controller的合体
@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String handle01(){
        return "Hello, Spring Boot 2!";
    }
}

Run springboot main method

Browser access to the corresponding address

http://localhost:8080/hello

success

Insert picture description here

How to pack

Import plugin

 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

Insert picture description here

How to run:
Enter the folder of the jar package,
start cmd
and enter the command java -jar file name, how many IU can start the project

application.properties file configuration

What can be configured in the file can refer to the official document
All configurations are in this

Notes on the main program

//这个注解是导入对应的类到ioc容器中
@Import({User.class, DBHelper .class} )
//这个注解表示是不是说有容器都用一个实例  false表示不是  true表示是
@Configuration( proxyBeanMethods = false)
//这个是根据条件创建  bean
@ConditionalOnMissingBean(name = "tom" )
//这个是导入Bean的Xml配置文件
@ImportResource("classpath: beans . xm1" )

Automatic binding (similar to reading properties file)


/**
 * 只有在容器中的组件,才会拥有SpringBoot提供的强大功能
 */
@Component
//读取在application.properties文件中mycar开头的文件如(mycar.brand)
@ConfigurationProperties(prefix = "mycar")
public class Car {
    private String brand;
    private Integer price;
}

Development tips

Lombok for javaBean

Import the corresponding package

 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

Then add the lombok plug-in to the idea.

Insert picture description here


A few notes about him:

//lombok的注解自动生成get,set方法
@Data
//自动生成tostring
@ToString
//自动生成构造方法(全部参)
@AllArgsConstructor
//自动生成无参构造方法
@NoArgsConstructor
//重写HashCode方法
@EqualsAndHashCode
@Component
//读取application.properties里面person开头的配置
@ConfigurationProperties(prefix = "person")
public class Person {
    private String sex;
    private Integer age;
}


Hot update dependency dev-tools

If you rely on pom.xml, it's ok


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

How to use Ctrl+F9 to update after code update

Quickly create a spring boot artifact Spring Initailizr

In idea, a new porject
select Spring Initailizr on the far right

Insert picture description here


Choose the scene you need to use on this page,
such as web mysql mybatis

Insert picture description here

He will automatically introduce dependencies and create the initial project structure

Configuration file

yaml

Basic syntax:

Key: value; there is a space between kv
Case sensitive
Use indentation to indicate hierarchical relationship
Tabs are not allowed for indentation, only spaces are allowed
. The number of spaces for indentation is not important, as long as the elements of the same level are aligned to the left,
'#' means comment
The string does not need to be quoted, if you want to add, "and"" means that the string content will be escaped/unescaped

• Literal: A single, indivisible value. date, boolean, string, number, null

k: v

Object: A collection of key-value pairs. map, hash, set, object

行内写法:  k: {k1:v1,k2:v2,k3:v3}
#或
k: 
  k1: v1
  k2: v2
  k3: v3

Array: A set of values ​​arranged in order. array, list, queue

行内写法:  k: [v1,v2,v3]
#或者
k:
 - v1
 - v2
 - v3

Example:
Person class:

package com.xzh.boot12.bean;

import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author XuZhuHong
 * @CreateTime 2021/6/7 18:40
 */
//绑定配置文件
@ConfigurationProperties(prefix = "person")
@Component
@ToString
@Data
public class Person {

    private String userName;
    private Boolean boss;
    private Date birth;
    private Integer age;
    private Pet pet;
    private String[] interests;
    private List<String> animal;
    private Map<String, Object> score;
    private Set<Double> salarys;
    private Map<String, List<Pet>> allPets;
}


application.yml configuration file:

# yaml表示以上对象
person:
  userName: zhangsan
  boss: false
  birth: 2019/12/12 20:12:33
  age: 18
  pet:
    name: tomcat
    weight: 23.4
  interests: [ 篮球,游泳 ]
  animal:
    - jerry
    - mario
  score:
    english:
      first: 30
      second: 40
      third: 50
    math: [ 131,140,148 ]
    chinese: { first: 128,second: 136 }
  salarys: [ 3999,4999.98,5999.99 ]
  allPets:
    sick:
      - { name: tom }
      - { name: jerry,weight: 47 }
    health: [ { name: mario,weight: 47 } ]

For the characters inside,
you can add double quotation marks and single quotation marks
. Double quotation marks have the same meaning as java.
Single quotation marks do not escape the string.

There is no prompt solution when configuring the file:

Import the following dependencies in pom.xml

  <!--yaml编写提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>



 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <!--这句话的意思是 让这个打包插件 不要把yaml的代码提示放进去-->
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

WEB development

Static resource access

As long as the static resources are placed in the classpath: called /static (or /public or /resources or /META-INF/resources
Access: current project root path/ + static resource name

Change the default static resource path

spring:
  mvc:
    #这里是改变他的访问地址
    static-path-pattern: /res/**
    #这个东西会影响 springboot的自定义欢迎页面失效

  resources:
    #这里是改变他默认的静态资源路径
    static-locations: [classpath:/haha/]

redis style open

Open in the configuration file:
here it is turned on in yml

spring:
  mvc:
    hiddenmethod:
      filter:
        enabled: true

Then set the corresponding request method in the controller

    //    @RequestMapping(value = "/user",method = RequestMethod.GET)
    @GetMapping("/user")
    public String getuser() {
        return "getuser user";
    }

    //    @RequestMaping(value = "/user", method = RequestMethod.POST)
    @PostMapping ("/user")
    public String postuser() {
        return "postuser user";
    }

    //    @RequestMapping(value = "/user", method = RequestMethod.DELETE)
    @DeleteMapping("/user")
    public String deleteuser() {
        return "deleteuser user";
    }

    //    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    @PutMapping("/user")
    public String putuser() {
        return "putuser user";
    }

It should be noted that the request method must be post, and there needs to be a label in the form whose name is _method and the value is the submitted method. This can be set to the hidden control layer to call it correctly.

<h1>欢迎页面</h1>
<form method="get" action="/user">
    <input type="submit" value="get">
</form>
<form method="post" action="/user">
    <input type="submit" value="post">
</form>
<form method="post" action="/user">
    <input name="_method" type="hidden" value="delete">
    <input type="submit" value="delete">
</form>
<form method="post" action="/user">
    <input name="_method" type="hidden" value="put">
    <input type="submit" value="put">
</form>

To change the value of name, you can do the following

@Configuration(proxyBeanMethods = false)
public class WebConfig {
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        //这个是设置那个name的名字
        hiddenHttpMethodFilter.setMethodParam("_m");
        return hiddenHttpMethodFilter ;
    }
}