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


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

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

    场景依赖选择界面

    默认项目包名

    pom.xml依赖文件

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

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

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

    1. <dependencies>
    2. <dependency>
    3. <groupId>org.springframework.boot</groupId>
    4. <artifactId>spring-boot-starter-web</artifactId>
    5. </dependency>
    6. </dependencies>

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

    1. org.springframework.boot
    2. spring-boot-maven-plugin

    遇到bug:

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

    1. /**
    2. * 主程序类
    3. * @SpringBootApplication:这是一个SpringBoot应用
    4. */
    5. @SpringBootApplication
    6. public class MainApplication {
    7. public static void main(String[] args) {
    8. SpringApplication.run(MainApplication.class,args);
    9. }
    10. }

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

    1. @RestController
    2. public class HelloController {
    3. @RequestMapping("/hello")
    4. public String handle01(){
    5. return "Hello, Spring Boot 2!";
    6. }
    7. }

    运行项目

    单元测试

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

    1. org.springframework.boot
    2. spring-boot-starter-test
    3. test

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

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

    1. import com.atguigu.boot.controller.HelloController;
    2. import org.junit.Test;
    3. import org.junit.runner.RunWith;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.test.context.SpringBootTest;
    6. import org.springframework.test.context.junit4.SpringRunner;
    7. @RunWith(SpringRunner.class)
    8. @SpringBootTest
    9. public class MainApplicationTests {
    10. @Test
    11. public void contextLoabs(){
    12. }
    13. @Autowired
    14. private HelloController helloController;
    15. public void HelloControllerTest(){
    16. String hello = helloController.handle01();
    17. System.out.println(hello);
    18. }
    19. }

    热部署

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

  • 相关阅读:
    java-net-php-python-springboot办公自动化系统计算机毕业设计程序
    java计算机毕业设计高校学生体温管理系统源码+mysql数据库+系统+lw文档+部署
    【跨境电商】EDM邮件营销完整指南(二):如何开展EDM营销活动
    海康监控视频无插件开发3.2版本运行demo
    MySQL中 JOIN关联查询的原理以及优化手段
    Git使用教程
    HTTP知识点总结
    redis的事务、锁机制、秒杀
    Java中对象的打印
    Linux内核设计与实现 第一章 Linux内核简介
  • 原文地址:https://blog.csdn.net/A6_107/article/details/126632361