本人已参与[新人创作礼]活动,一起开启掘金创作之路。
SpringBoot框架中还有两个非常重要的策略:开箱即用和约定优于配置。
开箱即用,Outofbox,是指在开发过程中,通过在MAVEN项目的pom文件中添加相关依赖包。
然后使用对应注解来代替繁琐的XML配置文件以管理对象的生命周期。
这个特点使得开发人员摆脱了复杂的配置工作以及依赖的管理工作,更加专注于业务逻辑。
约定优于配置(convention over configuration),也称作按约定编程,是一种软件设计范式,旨在减少软件开发人员需要的配置。
本质上是对系统、类库或框架中一些东西(如配置信息)假定一个大众化合理的默认值(缺省值)。
例如在模型中存在一个名为User的类,那么对应到数据库会存在一个名为user的表,只有在偏离这个约定时才需要做相关的配置(例如你想将表名命名为t_user等非user时才需要写关于这个名字的配置)。
一、入门案例
1.1 目录
1.2 pom.xml
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.hncj</groupId>
<artifactId>springboot-authority</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-authority</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.3 主方法
package cn.hncj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootAuthorityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAuthorityApplication.class, args);
}
}
1.4 config配置类
package cn.hncj.config;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created on 2022/4/29.
*
* @author Hou chaof
*/
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping
public String getById(){
System.out.println("spring boot running");
return "spring is running";
}
}
1.4 启动主类,访问http://localhost:8080/books
说明springboot项目运行成功!!!
二、入门案例分析:
pom.xml文件中,部分管理解释:
dependencyManagement :负责管理依赖;
pluginManagement:负责管理插件;
properties:负责定义依赖或插件的版本号。
2.1 pom.xml中的parent和starter
2.2 引导类
即下边这个类:
2.3 内嵌tomcat