SpringBoot2 简明教程

2023-07-29,,

1、环境配置:

●Java 8 & 兼容java14 .
●Maven 3.3+
●idea 2019.1.2

maven的settings.xml配置

<mirrors>
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>central</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
</mirrors> <profiles>
<profile>
<id>jdk-1.8</id>
<activation>
<activeByDefault>true</activeByDefault>
<jdk>1.8</jdk>
</activation>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
</properties>
</profile>
</profiles>

  

2、写一个HelloWorld项目

需求:浏览发送/hello请求,浏览器响应 Hello,Spring Boot 2

https://www.cnblogs.com/Kaelthas/p/17056262.html

2.1、SpringBoot的三大特性:依赖管理+自动配置+运行原理

2.1.1、基于父项目的 依赖管理

通过引入父项目,无需指定依赖的版本号,自动版本仲裁。但如果想引入特定版本,需要<properties>下的<XXX.version>标签

  <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>   //屏蔽父依赖,引入自己版本的 mysql
  <properties> <mysql.version>5.1.43</mysql.version> </properties>

2.1.2、自动装配

1)@SpringBootApplication

作用:标记为项目启动类,包含三个注解 { @SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan}

@ComponentScan:作用:额外指定扫描位置,可以指定多个

@SpringBootConfiguration:作用:标记为组件

@EnableAutoConfiguration:作用:又一个复合注解包含 @AutoConfigurationPackage 和 @Import,作用如下:

@AutoConfigurationPackage:扫描当前包
@Import({AutoConfigurationImportSelector.class}):注入 Selector 类
由于该过程需要加载配置文件 Spring-boot-autoconfigure/spring.factories(在 Spring-boot-autoConfiguration:2.3.4.jar 中可以看到)
相应的在 SpringFactoriesLoader 类,写明了该成员变量所在位置:
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

  META-INF/spring.factories 的截图如下:

总而言之:

    SpringBoot在启动的时候从classpath下springboot-autoconfigure.jar的META-INF/spring.factories中获取所有EnableAutoConfiguration初始值

    根据 pom.xml 引入的依赖,启动需要的配置

转自:狂神说SpringBoot2


2)@Configuration 和 @Bean

@Configuration 指定某个类为配置文件,其作用是向IOC容器中添加Bean,分为Full模式和Lite模式。

Full 模式:如果注入到容器中的多个 bean 实例之间有依赖关系时,建议使用 Full 模式,默认使用 Full 全模式。

Lite 模式:在同一个Configuration配置类中,注入到容器中的 bean 实例之间没有依赖关系时,建议使用 Lite 轻量级模式,@Configuration(proxyBeanMethod=false) ,每次启动不用检测直接返回新的实例对象(不保证单例模式),以提高 springboot 的启动速度。

实例详解: https://www.cnblogs.com/Kaelthas/p/17059554.html

3)@Import

直接注入模式 ,为IOC容器添加 Bean 对象,此时Bean对象的名称为类名

/**
*使用Import 将指定的类的实例注入至Spring 容器中
*/
@Import({Customer.class,Broker.class})
public class ImportDirect {
// TODO
}

  实例详解:https://blog.csdn.net/tuoni123/article/details/80213050


2.2.3 启动一个服务

SpringApplication.run(MAIN.class, args);

这条语句,背后执行了四个功能

1)判断项目是普通项目还是 web 项目

2)查找并加载所有可用初始化器 initializer

3)查找并加载所有可用监听器 listener

4)找到运行主类 main


3、SpringBoot 配置文件

全局配置文件有两种,application.properties 和 application.yml

application.properties

语法结构 :key=value

application.yml

语法结构 :key:空格 value

配置文件的作用:修改 SpringBoot 的默认值

需求:写两个Bean,通过yaml赋值,然后将Bean输出到控制台

解析:

Bean注解@Component,标记组件;
Bean注解@ConfigurationProperties(prefix = "tom")添加配置文件字段头tom,引入依赖<artifactId>spring-boot-configuration-processor</artifactId>
<artifactId>spring-boot-starter-test</artifactId>,引入Junit依赖(父依赖中没有)

写两个Bean:User、Pet

package com.itheima.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; @Component
@ConfigurationProperties(prefix = "user01")
public class User {
String name;
int age;
Pet pet; public User() {
} public User(String name,int age) {
this.name = name;
this.age = age;
} public User(String name, int age, Pet pet) {
this.name = name;
this.age = age;
this.pet = pet;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Pet getPet() {
return pet;
} public void setPet(Pet pet) {
this.pet = pet;
} @Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", pet=" + pet +
'}';
}
} package com.itheima.bean; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; @Component
@ConfigurationProperties(prefix = "tom")
public class Pet { String name; public Pet() { } public Pet(String name) {
this.name = name;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public String toString() {
return "Pet{" +
"name='" + name + '\'' +
'}';
}
}

  写一个运行类

package com.itheima;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext; /**
* @SpringBootApplication 标记为SpringBoot应用,作为项目启动类
*/ @SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run =
SpringApplication.run(MainApplication.class, args);
}
}

  test类,注意测试资源也要放yaml文件

package com.itheima;

import com.itheima.bean.Pet;
import com.itheima.bean.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest
public class MainApplicationTest {
@Autowired
private User user01;
@Autowired
private Pet pet;
@Test
public void contestLoads(){
System.out.println(user01);
System.out.println(pet);
} }

  yaml配置文件

user01:
name: zhangsan
age: 18
pet: tom tom:
name: tom

  结果:

  

jsr303 数据校验

配置文件的位置:项目根目录、项目根目录下的config文件夹、resources文件夹、resources文件夹下config文件夹,优先级从高到低

新建一个SpringBoot项目,应该解决哪些问题?

导入静态资源
首页
jsp,模板引擎Thymeleaf
装配扩展SpringMVC
增删改查
拦截器
国际化

静态资源文件  源文件:WebMvcAutoConfiguration.java

"classpath:/META-INF/resources/"
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"

public: 一般存放公共的文件,比如js
static: 一般存放静态资源: 比如图片
resources:可以在里面设置upload文件夹,用于存放上传的文件

总结:
  在springboot,我们可以使用以下方式处理静态资源

  public,static,/**,resources,直接使用localhost:8080/浏览器访问,优先级: resources>static (默认)>public

首页定制  源文件:WebMvcAutoConfiguration.java

WebMvcAutoConfiguration.java下有welcomepage的代码,其中使用到了ResourcesProperties.java文件,该文件包括一个字段 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};该路径下的静态资源文件直接会被调用。

Thymeleaf 为 Controller 跳转自动添加前后缀

<!--引入thymeleaf的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

这样Controller返回的字符串能自动跳转到 Resources/templates/index.html,因为 Thymeleaf 自动添加了前后缀

Controller:

package com.kuang.controller;
@Controller
public class IndexController {
@RequestMapping("/index")
public String IndexController(){
return "index";
}
}

ThymeleafProperties 添加前后缀:

public class ThymeleafProperties {
private String prefix = "classpath:/templates/";
private String suffix = ".html";

jsp和Thymeleaf 语法:

Thymeleaf 教程:https://www.cnblogs.com/Kaelthas/p/17068768.html

Order Feature Attributes 解释
1 Fragment inclusion th:insert
th:replace
include
2 Fragment iteration th:each 循环
3 Conditional evaluation th:if
th:unless
th:switch
th:case
条件
4 Local variable definition th:object
th:with
 
5 General attribute modification th:attr
th:attrprepend
th:attrappend
 
6 Specific attribute modification th:value
th:href
th:src
...
 
7 Text (tag body modification) th:text
th:utext
 
8 Fragment specification th:fragment  
9 Fragment removal th:remove  

后台管理系统

新建项目 java版本 和sdk 都是1.8

下一步:勾选依赖组件

SpringBoot DevTools: 实时编译

lombok: 简化 javabean开发

Spring Configuration Processors: 自定义配置代码提示

SpringWeb: 开发web

Thymeleaf: 开发模板

删除没用的文件 .mvn、.gitgnore、HELP.md、 mvnw、 mvnw.cmd

将静态资源css、fonts、images、js等静态文件夹,放到 /resources/static 下

数据库

可以修改这个配置项@ConfigurationProperties(prefix = "spring.jdbc")来修改JdbcTemplate

@RestController 等价于@Controller+@ResponseBody

@Controller 注入IOC容器

@ResponseBody 以Json形式返回数据

@RequestMapping 标记类或者方法,指定浏览器访问路径

@GetMapping 发出get请求

@Component(标记为组件类,把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>,与@Autowired连用)

@Controller 标记为Controller,注入到容器

@Services 提供被注入的类,写业务逻辑

@Repository 用于声明 dao 层的 bean

@Component、@Controller、@Services、@Repository的作用

@Mapper 与 @MapperScan:使用 Mybatis 有 XML 文件或者注解的两种使用方式,如果是使用 XML 文件的方式,我们需要在配置文件中指定 XML 的位置

Service层需要使用@Autowired或@Resource注解注入后调用Mapper里的方法时,需要将这些接口注入到Spring上下文中。有两种方法可以完成注入:
在每个类*Mapper的接口上都加一个@Mapper注解。
在SpringBoot的启动类上加一个@MapperScan并指明包路径。

直接在每个对应的Mapper类上面添加注解@Mapper。Mapper类较多时,这样使用比较麻烦。

方法二:使用扫描注解@MapperScan

@MapperScan("com.hadoopx.issue.mapper")

@MapperScan({"com.hadoopx.issue.mapper","com.hadoopx.test.mapper","com.hadoopx.paper.mapper"})

@MapperScan("com.hadoopx.*.mapper")

@MapperScan("com.hadoopx.**.mapper")

@Mapper 是 Mybatis 的注解,和 Spring 没有关系,@Repository 是 Spring 的注解,用于声明一个 Bean。(重要)

@Bean

标记方法返回一个Bean组件,用于注入

@Configuration

用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。

 

SpringBoot2 简明教程的相关教程结束。

《SpringBoot2 简明教程.doc》

下载本文的Word格式文档,以方便收藏与打印。