文章目录
前言
SpringBoot的三种创建方式,启动类上的注解,parent的理解。
SpringBoot的三种创建方式
根据官网创建
通过点击右上角的Add Dependencies添加依赖,这里添加了一个web依赖
直接通过idea导入就可以运行了
根据IDE开发工具创建
IDE(integrated development environment)
点击idea的左上角File选项,依次选择File->New->Project->Spring Initializr
可以看到其实也是通过https://start.spring.io/创建的,只不过IDE帮忙解压导入了
信息填写和网页版一直,就不赘述了.
手动创建
Spring Boot实际上也是一个maven项目,只需手动编写pom.xml,并创建一个启动类就可以了
注意启动类不能在项目java根目录下
可以通过官方文档快速编写
https://docs.spring.io/spring-boot/docs/current/reference/html/getting-started.html#getting-started-first-application
启动类上的注解
//JDK注解用来标注这个注解类的使用范围和使用时间等
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
//spring的注解
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
@SpringBootApplication 等价于@Configuration,@EnableAutoConfiguration,@ComponentScan.
@EnableAutoConfiguration用于激活Spring Boot自动装配机制
@ComponentScan激活@Component的扫描
@Configuration声明被标注类为配置类
parent和dependencyManagement
parent的理解
maven中parent的效果等同于java类中的extend,所以声明了
<parent>
<artifactId>spring-boot-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.2.11.RELEASE</version>
</parent>
后pom设置依赖不需要添加<version></version>标签,就是因为其父类中已经声明了版本管理,子pom直接添加就可以了
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
通过添加可以指定非resources目录下的非.java文件打包
<build>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/</directory>
<includes>
<include>**/*.yml</include>
</includes>
</resource>
</resources>
</build>
dependencyManagement
因为是pom文件是单继承的,有时当需要依赖公司的或自己定义的parent时,对于spring-boot-starter-parent的一些配置就无法使用了.但是又需要使用时,就可以引入dependencyManagement标签
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.11.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
这样一些spring帮忙定义好的version又可以使用了.
值得注意的是,由于dependencyManagement只关心dependency
,所以spring-boot-dependencies定义在pluginManagement中管理的插件版本就无法使用了,需要手动引入版本
参考文档
maven设定项目编码
创建一个 Spring Boot 项目,你会几种方法?
你真的理解 Spring Boot 项目中的 parent 吗?