注:此文中主要是用于创建项目过程的一个参考,实际下方第四步中有张图自己忘记截图了,然后就在csdn参考其他博主里的文章找了一张图代替,图片信息本身是没有错误的,只是作为一个参考。这里直接需要注意一下包名
第一步:
第二步:
第三步:
第四步:
第五步
第六步:
第七步:
第八步:测试结果
controller代码
package com.springboot.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * 注意:用 @controller 注解是渲染页面用的,即可以最后返回一个页面,且返回页面还需要导入thymeleaf模版 * 前端返回页面用的模版依赖 * <dependency> * <groupId>org.springframework.boot</groupId> * <artifactId>spring-boot-starter-thymeleaf</artifactId> * </dependency> * 用 @restController,是返回数据用的,如 json格式数据,字符串等等 */ @RestController public class UserController { @GetMapping("/hello") public String SayHello(){ String hello = "SpringBoot项目成功运行!!!"; System.out.println("SayHello 已经运行成功!!!"); return hello; } }
测试代码
package com.springboot.demo; import com.springboot.demo.controller.UserController; import org.junit.jupiter.api.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 class DemoApplicationTests { @Test void contextLoads() { } @Autowired private UserController userController; @Autowired public void sayHelloTest(){ String hello = userController.SayHello(); System.out.println(hello); } }
配置文件
<?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.5.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.springboot</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</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> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>