猿创征文|搭建第一个Spring Boot项目

IDEA 旗航版本新建SpringBoot项目,file-new-Project-Spring Initializr。

当然,这一步也可以构建Maven来创建框架,新建项目一样

场景依赖选择界面

默认项目包名

pom.xml依赖文件

添加spring-boot-starter-parent依赖是Spring Boot框架集成项目的统一父类管理依赖,添加该依赖后可以使用Spring Boot的相关特性,<version>是指Spring Boot的版本号

父项目做依赖项目 
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
</parent>

添加spring-boot-starter-web依赖是SpringBoot框架对web开发场景集成支持的依赖启动器,添加该依赖后就可以自动导入Spring MVC框架相关依赖进行web开发

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>

项目打包插件,直接在服务器执行

 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

遇到bug:

在/src/main/java开发目录下创建主程序MainApplication类,@SpringBootApplication注释是SpringBoot用于MainApplication类作为主程序启动类

/**
 * 主程序类
 * @SpringBootApplication:这是一个SpringBoot应用
 */
@SpringBootApplication
public class MainApplication {

    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class,args);
    }
}

创建HelloController的请求处理控制类编写业务

@RestController
public class HelloController {


    @RequestMapping("/hello")
    public String handle01(){
        return "Hello, Spring Boot 2!";
    }


}

运行项目

单元测试

实际开发中,每当完成一个功能接口或业务方法的编写后,在测试类检验该功能是否正确,添加spring-boot-starter-test测试依赖启动器

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

编写单元测试类和测试方法

在/src/test/java测试目录下创建与项目主程序对应的单元测试类

import com.atguigu.boot.controller.HelloController;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MainApplicationTests {
    @Test
    public void contextLoabs(){

    }
    @Autowired
   private HelloController helloController;
        public void HelloControllerTest(){
            String hello = helloController.handle01();
            System.out.println(hello);
        }
}

热部署

通常会对一段业务不断地修改测试,在修改之后往往需要重新启动服务,有些服务启动需要加载很长时间才能启动成功,添加spring-boot-devtools热部署依赖启动,测试效果,在不关闭当前项目的情况下,修改HelloController的handle01()方法返回值,刷新浏览器。

猜你喜欢

转载自blog.csdn.net/A6_107/article/details/126632361