百度百科:
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
自我理解:
SpringBoot是一个基于Spring框架的可以快速开发Web应用的轻量型框架,以前的Spring在开发Web应用的时候需要借助MVC,配置很多配置文件,整合MyBatis需要Spring和Mybatis的整合依赖以及配置文件等,SpringBoot的出现使得这一复杂的配置简化为了注解的方式。
In short, the microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies.
SpringBoot官方文档
https://docs.spring.io/spring-boot/docs/2.7.14/reference/html/
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.4.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
dependencies>
package com.lzx.springboot.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// TODO SpringBoot主程序入口
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class,args);
}
}
在java包下一定要包否则会报错
package com.lzx.springboot.main.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController //包括 @Controller、@ResponseBody ==> 在浏览器中写入hello,SpringBoot 2!
public class HelloController {
@RequestMapping("/hello")
public String hello01() {
return "hello,SpringBoot 2!";
}
}
页面路由发生变化只是会在页面输出,不会发生页面跳转,需要用@ResponseBody进行标注。@RestController包含了@Controller、@ResponseBody两个注释
直接点击绿色箭头进行运行,不需要添加Tomcat服务器
在application.properties配置文件配置项目的文件
server.port=8888
参考SpringBoot配置的官方文档:https://docs.spring.io/spring-boot/docs/2.7.14/reference/html/application-properties.html#appendix.application-properties
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
项目打包成"jar"文件
:已经打包的项目中的端口号若想修改需要吃重新打包
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.4.RELEASEversion>
parent>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-dependenciesartifactId>
<version>2.3.4.RELEASEversion>
parent>
<properties>
<activemq.version>5.15.13activemq.version>
<antlr2.version>2.7.7antlr2.version>
<appengine-sdk.version>1.9.82appengine-sdk.version>
<artemis.version>2.12.0artemis.version>
<aspectj.version>1.9.6aspectj.version>
<assertj.version>3.16.1assertj.version>
<atomikos.version>4.0.6atomikos.version>
<awaitility.version>4.0.3awaitility.version>
<bitronix.version>2.1.4bitronix.version>
<build-helper-maven-plugin.version>3.1.0build-helper-maven-plugin.version>
..............
properties>
spring-boot-dependencies的文件中包含了很多已经内置的文件,导入他的子类就可以导入对应的配置文件对应的版本号
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starterartifactId>
<version>2.3.4.RELEASEversion>
<scope>compilescope>
dependency>
spring-boot-starter:场景启动器,引入它以后它对应的场景所需要的常规依赖就可以注入完毕了
SpringBoot所有支持的场景如以下网址:
https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter
引入依赖的时候可以不写版本号,除非引入非版本仲裁的jar,必须写版本号
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-tomcatartifactId>
<version>2.3.4.RELEASEversion>
<scope>compilescope>
dependency>
引入SpringMVC全套组件
自动配好SpringMVC常用组件(功能)
SpringBoot已经配置了所有web开发的常见场景
默认添加@SpringBootApplication注释以后,标注的主程序所在的包及其下方的所有的包里面的组件都会被默认扫描出来
若想改变扫描包的路径:@SpringBootApplication(scanBasePackages=“xxxx”)或者使用ComponentScan指定扫描路径。
@SpringBootApplication
等同于
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("xxxxxxx")
需要哪个场景就导入哪个starter,导入以后对应的场景就会开启,SpringBoot所有的自动配置功能都会在spring-boot-autoconfigure
@Configuration通常标注一个类,@Bea通常标注一个方法,他们通常搭配使用。
简单粗暴理解就是:@Configuration标注的类相当于以前在Spring中配置的一个XML文件(用于创建对象的文件),@Bean表示的方法相当于原Spring文件中
标签。
两个模式
测试实例
@Configuration(proxyBeanMethods = false) //创建的对象都是新创建的
public class MyConfiguration {
@Bean //创建对象,相当于标签
public User user() {
User zhangsan = new User("zhangsan",18);
//user组件依赖了pet组件
zhangsan.setPet(tomcatPet());
return zhangsan;
}
@Bean("tom")
public Pet tomcatPet() {
return new Pet("tomcat");
}
}
若按照上述写法的话会有错误,在@Configuration(proxyBeanMethods = false)限制了@Bean之间不能有关联
上述的错误意思是:在@Configuration参数中proxyBeanMethods设置为了false,直接调用了带有@Bean的方法,将proxyBeanMethods设置为true或者使用依赖注入DI。
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
//返回IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//查看容器中的组件
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println("容器中的组件名称: " + name);
}
//从容器中获取容器
Pet tom = run.getBean("tomcatPet", Pet.class);
Pet tom1 = run.getBean("tomcatPet", Pet.class);
System.out.println("组件:" + (tom == tom1));
MyConfiguration myConfiguration = run.getBean(MyConfiguration.class);
System.out.println("myConfiguration = " + myConfiguration);
}
按照上述写法,会报错,按理来说IOC容器中获取bean对象,默认方法名就是id、可按照上述写法还是会报错。
解决办法
将main()方法中的@SpringBootApplication注释修改为@SpringBootConfiguration、@EnableAutoConfiguration
@ComponentScan(“xxxxx”)的组合,注意:不是@SpringBootApplication和他们的组合是@SpringBootConfiguration,否则的话也会报错。
冗余声明:@SpringBootApplication已经声明了@EnableAutoCinfiguration,在@Bean中设置名称以后在容器创建以后获取对象时候不能在使用方法名获取,否则会报错:No bean named “xxx” available
package com.lzx.springboot.main;
import com.lzx.springboot.config.MyConfiguration;
import com.lzx.springboot.entity.Pet;
import com.lzx.springboot.entity.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.lzx.springboot")
public class MainApplication {
public static void main(String[] args) {
//返回IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
//查看容器中的组件
String[] names = run.getBeanDefinitionNames();
for (String name : names) {
System.out.println("容器中的组件名称: " + name);
}
//从容器中获取容器
Pet tom = run.getBean("tom", Pet.class);
Pet tom1 = run.getBean("tom", Pet.class);
System.out.println("组件:" + (tom == tom1));
MyConfiguration myConfiguration = run.getBean(MyConfiguration.class);
System.out.println("myConfiguration = " + myConfiguration);
User user = myConfiguration.user();
User user1 = myConfiguration.user();
System.out.println("User组件:" + (user == user1));
User user2 = run.getBean("user", User.class);
Pet tom2 = run.getBean("tom",Pet.class);
System.out.println("用户的宠物是:" + (user2.getPet() == tom2));
}
}
因MyConfiguration被@Configuration(proxyBeanMethods = true)标识,故为Full模式,此模式下被@Bean标识的方法无论被调用多少次,都是单例对象,保证各个类组件之间有依赖关系。
详细说明:Bean注解用于在Spring容器中创建一个bean对象,被标识的地方返回一个对象,Spring将该对象注册为一个bean,使其他组件可以使用,一般都是和@Configuration一起使用,一般标识在方法上。
实例
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}
详细说明:Component注解用于标识一个普通的spring bean组件,一般表示在类上。
实例
@Component
public class MyComponent {
//代码逻辑
}
详细说明:Controller注解用于标识一个类是SpringMVC中的控制器组件,用于处理客服端请求和返回相应的响应结果。
实例
@Controller
public class MyController {
@RequestMapping("/hello")
public String hello() {
return "Hello, World!";
}
}
详细说明:Service注解用于标识一个类是Service服务层的组件,主要封装业务逻辑。
实例
@Service
public class UserService {
public void createUser(User user) {
// 创建用户的业务逻辑
}
}
详细说明:Reposity注解用于标识一个类是数据访问层的组件,通常用于数据库交互
实例
@Service
public class UserService {
public void createUser(User user) {
// 创建用户的业务逻辑
}
}
详细说明:ComponentScan注解用于指定Spring中进行组件扫描时所需要扫描的包和类路径
实例
@Configuration
@ComponentScan("xxxxx")
public class AppConfig {
// 配置代码
}
详细说明:Import注解用于引入其他的配置类和组件类,将他们收纳到当前的配置类的上下文中。
实例
@Configuration
@Import({OtherConfig.class, OtherComponent.class})
public class AppConfig {
// 配置代码
}
条件装配:满足Conditional条件进行注入
@Configuration(proxyBeanMethods = true) //各个类之间不能有依赖关系,创建的对象都是新创建的
@ConditionalOnMissingBean(name = "tom")
public class MyConfiguration {
}
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.lzx.springboot")
public class MainApplication {
public static void main(String[] args) {
//返回IOC容器
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
boolean tom = run.containsBean("tom");
System.out.println("容器中的Tom组件:" + tom);
boolean user01 = run.containsBean("user01");
System.out.println("容器中的user01组件:" + user01);
boolean tom22 = run.containsBean("tom22");
System.out.println("容器中的tom22组件:" + tom22);
}
将Java读取的properties文件中的内容,封装到JavaBean中
通常ConfigurationProperties注解和EnableConfigurationProperties 一起使用,EnableConfigurationProperties 用于开启对@ConfigurationProperties注解类的配置
@EnableConfigurationProperties(Car.class)
//1、开启Car配置绑定功能
//2、把这个Car这个组件自动注册到容器中
public class MyConfig {
}
作用:简化JavaBean的配置
在pom.xml文件中添加以下依赖:
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
在IDEA中搜索Lombok下载
===============================简化JavaBean开发===================================
@NoArgsConstructor
//@AllArgsConstructor
@Data
@ToString
@EqualsAndHashCode
public class User {
private String name;
private Integer age;
private Pet pet;
public User(String name,Integer age){
this.name = name;
this.age = age;
}
}
================================简化日志开发===================================
@Slf4j
@RestController
public class HelloController {
@RequestMapping("/hello")
public String handle01(@RequestParam("name") String name){
log.info("请求进来了....");
return "Hello, Spring Boot 2!"+"你好:"+name;
}
}
作用:在修改项目或者页面以后,按住ctrl + F9;
在pom.xml文件中添加以下依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<optional>trueoptional>
dependency>
1、选择新建模块或者新建项目(此处是以新建模块为例)
2、修改项目配置
3、选择想要添加的配置
4、选择文件位置
同以前Properties的用法
YAML,用来表达数据序列化的格式。是"YAML Ain’t a Markup Language"(YAML不是一种标记语言)的递归缩写。在开发的这种语言时,YAML的意思其实是:“Yet Another Markup Language”(仍是一种标记语言),但为了强调这种语言以数据做为中心,而不是以标记语言为重点,而用反向缩略语重命名。
YAML非常适合用来做以数据为中心的配置文件。
k: v
行内写法: k: {k1:v1,k2:v2,k3:v3}
#或
k:
k1: v1
k2: v2
k3: v3
行内写法: k: [v1,v2,v3]
#或者
k:
- v1
- v2
- v3
# yaml表示上述对象
person:
userName: zhangsan
boss: false
birth: 20919/12/12
age: 18
pet:
name: tomcat
weight: 23.4
interests: [篮球,游泳]
animal:
-jerry
-mario
sorce:
english: # 按照map集合的写法
first: 30
second: 40
third: 50
math: [143,45,4]
chinese: {first: 123} # 按照map集合的写法
salarys: [125,45,78,56]
allPets:
sick:
- {name: tom}
- {name: jerry,weight: 21}
heakthy: [{name: mario,weight: 45}]
自定义的类和配置文件绑定一般没有提示。
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
<optional>trueoptional>
dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
exclude>
excludes>
configuration>
plugin>
plugins>
build>
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.(大多场景我们都无需自定义配置)
The auto-configuration adds the following features on top of Spring’s defaults:
Inclusion of ContentNegotiatingViewResolver
and BeanNameViewResolver
beans.
Support for serving static resources, including support for WebJars (covered later in this document)).
Automatic registration of Converter
, GenericConverter
, and Formatter
beans.
Converter,GenericConverter,Formatter
Support for HttpMessageConverters
(covered later in this document).
HttpMessageConverters
(后来我们配合内容协商理解原理)Automatic registration of MessageCodesResolver
(covered later in this document).
MessageCodesResolver
(国际化用)Static index.html
support.
Custom Favicon
support (covered later in this document).
Favicon
Automatic use of a ConfigurableWebBindingInitializer
bean (covered later in this document).
自动使用 ConfigurableWebBindingInitializer
,(DataBinder负责将请求数据绑定到JavaBean上)
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration
class of type WebMvcConfigurer
but without @EnableWebMvc
.
不用@EnableWebMvc注解。使用 **@Configuration**
+ **WebMvcConfigurer**
自定义规则
If you want to provide custom instances of RequestMappingHandlerMapping
, RequestMappingHandlerAdapter
, or ExceptionHandlerExceptionResolver
, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations
and use it to provide custom instances of those components.
声明 **WebMvcRegistrations**
改变默认底层组件
If you want to take complete control of Spring MVC, you can add your own @Configuration
annotated with @EnableWebMvc
, or alternatively add your own @Configuration
-annotated DelegatingWebMvcConfiguration
as described in the Javadoc of @EnableWebMvc
.
使用 **@EnableWebMvc+@Configuration+DelegatingWebMvcConfiguration 全面接管SpringMVC**
静态资源放在类路径下: called /static
(or /public
or /resources
or /META-INF/resources
访问:当前项目根目录 + 静态资源名
原理:静态映射/**;
客户端发出请求以后,先在Controller处理,若不能处理就将所有的请求交给静态资源处理器,若静态资源处理器找不到则会报出404页面未找到
默认无前缀
spring:
mvc:
static-path-pattern: /res/**
自动映射 /webjars/**
pom.xml文件引入以下依赖
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>jqueryartifactId>
<version>3.5.1version>
dependency>
访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径
静态资源路径下 index.html
spring:
# mvc:
# static-path-pattern: /res/** 这个会导致welcome page功能失效
resources:
static-locations: [classpath:/haha/]
favicon.ico放在静态资源目录下即可
spring:
# mvc:
# static-path-pattern: /res/** 这个会导致 Favicon 功能失效
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {}
@Configuration(proxyBeanMethods = false)
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {}