一.快速搭建SpringBoot应用
1. 创建一个maven项目。pom.xml文件中添加如下的内容。
spring-boot-starter-parent 才能继承父项目中所有的依赖。
其父项目为spring-boot-starter-dependencies, 定义好了组件版本、组件坐标、插件管理。
帮我们管理了springboot中的所有依赖版本,解决了版本冲突的问题。叫做版本仲裁中心
spring-boot-starter-xxx. 以spring-boot-starter-web为例,其中定义好了web开发时所需的大部分依赖。 帮我们整合了第三方库,做了默认配置。需要修改的话到application.properties中修改
plugin: 生成的jar包能都用java -jar独立运行
spring-boot-configuration-processor: 在编写配置文件的时候有自动提示。 IDEA的Annotation Processors 要勾选Enable annotation procession
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.3.RELEASE</version>
</plugin>
</plugins>
</build>
2. 编写controller,标记RequestMapping() 指定映射路径
3. SpringBoot启动入口, 使用@SpringBootAppication注解标记。在类中运行springApplication.run()
4. 在Resoures文件夹下加上配置文件 application.properties, 可以配置一些项目属性,比如端口等
5. 创建springBoot父项目。创建好一个maven项目,在该maven项目中创建modules。要在父项目的pom中加上<packaging>pom<packaging>
二. 自动配置原理解析
登录 | ProcessOn
查看启动类上的注解@SpringBootApplication
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration *****等同与@Configuration,既标注该类是Spring的一个配置类
@EnableAutoConfiguration *****SpringBoot自动配置功能开启
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {...}
按住Ctrl点击查看注解@EnableAutoConfiguration。 告诉SpringBoot去开启自动配置类,会自动加载自动配置类,{ AutoConfigurationImportSelector}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage \\将当前所在包路