Post

springboot_01

springboot_01

springboot

Spring Boot 四个层

展示层: 表示层负责处理HTTP请求,将JSON参数转换为对象,并对请求进行身份验证并将其传输到业务层。简而言之,它由视图即前端部分组成。

业务层: 业务层处理所有业务逻辑 >。它由服务类组成,并使用数据访问层提供的服务。它还执行授权和验证。

持久层: 持久层包含所有存储逻辑,并将业务对象与数据库行进行相互转换。

数据库层: 在数据库层中, CRUD (创建,检索,更新,

启动

maven依赖下载完 application.properties加,run一下就可以了 访问 localhost:8088

1
2
3
4
5
6
server.port=8088

spring.datasource.url=jdbc:mysql://localhost:3306/transmoney
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

lombok

  1. idea要下载Lombok插件
  2. maven依赖
1
2
3
4
5
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.18</version>
</dependency>

常用

@Getter/@Setter

自動產生 getter/setter

@ToString

自動 override toString() 方法,會輸出所有變數的值

@EqualsAndHashCode

自動生成 equals(Object other) 和 hashcode() 方法,包括所有的「非靜態變數」和「非 transient 變數」 如果某些變數不想要加進判斷,可以透過 exclude 排除(或是也可以反過來,使用 of 指定只要輸出某些字段)

@NoArgsConstructor、@AllArgsConstructor、@RequiredArgsConstructor

在自動生成該 Class 的 constructor,差別只是在「生成的 constructor 的參數不一樣」而已

@NoArgsConstructor : 生成一個沒有參數的 constructor @AllArgsConstructor : 生成一個包含所有參數的 constructor 當我們沒有指定 constructor 時,Java compiler 會幫我們自動生成一個沒有任何參數的 constructor 給該 Class,但是如果我們自己寫了 constructor 之後,Java 就不會自動幫我們補上那個無參數的 constructor 了 @RequiredArgsConstructor : 生成一個包含「特定參數」的 constructor,特定參數指的是「那些有加上 final 修飾詞的變數們」

@Data(最常用)

只要加了 @Data,等於同時加了以下註解:

  • @Getter/@Setter
  • @ToString
  • @EqualsAndHashCode
  • @RequiredArgsConstructor

@Value

他會把所有的變數都設成 final,其他的就跟 @Data 一樣,等於同時加了以下註解:

  • @Getter(注意沒有 @Setter)
  • @ToString
  • @EqualsAndHashCode
  • @RequiredArgsConstructor

@Builder(常用)

自動生成流式 set 值寫法

User user = User.builder().id(1).name(“John”).build(); 等价于 User user = new User(); user.setId(1); user.setName(“John”)

@Slf4j

自動生成該 Class 的 log 變數,要打日誌就可以直接打

@SpringBootApplication

1
2
3
4
5
6
7
8
// 定义
@Target({ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME) 
@Documented 
@Inherited 
@SpringBootConfiguration //它继承自 @Configuration 注解,功能也跟 @Configuration 一样。它会将当前类标注为配置类了,我们在启动类中配置 Bean 就可以生效了
@EnableAutoConfiguration //启动自动配置。开启自动配置后, Spring Boot 会扫描项目中所有的配置类,然后根据配置信息启动 Spring 容器。
@ComponentScan(excludeFilters = {@org.springframework.context.annotation.ComponentScan.Filter(type = org.springframework.context.annotation.FilterType.CUSTOM, classes = {org.springframework.boot.context.TypeExcludeFilter.class}),@org.springframework.context.annotation.ComponentScan.Filter(type = org.springframework.context.annotation.FilterType.CUSTOM, classes = {org.springframework.boot.autoconfigure.AutoConfigurationExcludeFilter.class})}) //注解,用来指定我们要扫描的包

模板引擎

常见的有 FreeMarker 、 Thymeleaf 、 JSP

RESTful 风格

swagger2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>demo</description>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.6.13</spring-boot.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                    <mainClass>com.demo.demo_01.DemoApplication</mainClass>
                    <skip>true</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

必须要在 application.properties 加 spring.mvc.pathmatch.matching-strategy=ant_path_matcher 才能运行 springfox

配置文件

1
2
# 项目路径
server.servlet.context-path=/spring-boot-profile

.properties 配置使用顿号分割语义,而 .yml 配置使用缩进分割语义。 @Value 注解注入配置项的值

1
2
3
4
5
6
7
8
9
@Component//注册为组件
public class WxMpParam {
	@Value("${wxmp.appid}")//注入wxmp.appid配置项
	private String appid;
	@Value("${wxmp.secret}")//注入wxmp.secret配置项
	private String secret;
  //省略get set方法
}

打包与部署

  1. jdk

  2. mvn clean package -Dmaven.test.skip=true

  • mvn clean

清理项目的输出目录(默认是 target 目录)。 删除上一次构建生成的文件,比如 .class 文件、JAR 文件、WAR 文件等。

  • package

执行 Maven 的 package 生命周期阶段,编译代码、运行资源处理器,然后将代码打包为指定的分发格式(例如 JAR 或 WAR)。 生成的包通常会存放在 target 目录下。

  • -Dmaven.test.skip=true

跳过所有测试,不运行单元测试或集成测试。 作用范围:会完全跳过编译和执行测试代码,节省构建时间。

  1. target目录

数据访问

跨域配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * 跨域配置类
 */
@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")// 对所有请求路径
                        .allowedOrigins("*")// 允许所有域名
                        .allowCredentials(false)
                        .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH")// 允许所有方法
                        .maxAge(3600);
            }
        };
    }
}

集成 druid

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

1
2
3
4
5
6
<!-- springboot druid -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid-spring-boot-starter</artifactId>
	<version>1.2.8</version>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;


/**
 * Druid配置
 */
@Configuration
public class DruidConfig {
    /**
     * 注册servletRegistrationBean
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),
                "/druid/*");
        servletRegistrationBean.addInitParameter("allow", "");
        // 账号密码
        servletRegistrationBean.addInitParameter("loginUsername", "root");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        servletRegistrationBean.addInitParameter("resetEnable", "true");
        return servletRegistrationBean;
    }

    /**
     * 注册filterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        // 添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}

JPA 数据持久层

Hibernate

spring.jpa.hibernate.ddl-auto=update

1
2
3
4
5
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

不用写SQL,自动创建表 CrudRepository

MyBatis

运行

Cron 表达式

从左到右一共 6 个位置,分别代表秒、时、分、日、月、星期,以秒为例:

如果该位置上是 0 ,表示在第 0 秒执行; 如果该位置上是 * ,表示每秒都会执行; 如果该位置上是 ? ,表示该位置的取值不影响定时任务,由于月份中的日和星期可能会发生意义冲突,所以日、 星期中需要有一个配置为 ? 。 按照上面的理解,cron = “0 * * * * ?” 表示在每分钟的 00 秒执行、cron = “0 0 0 * * ?” 表示在每天的 00:00:00 执行。

This post is licensed under CC BY 4.0 by the author.