创建springboot项目有多种方式
本文就是使用maven创建springboot项目做一个记录
-
创建maven项目,按下面的选择,然后就一直next
-
创建项目进来后,修改pom文件(主要添加springboot的父级依赖,以及一些起步依赖包,如starter-web,starter-test,devtools等)
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.lys</groupId> <artifactId>blog-parent</artifactId> <version>1.0-SNAPSHOT</version> <parent> <artifactId>spring-boot-starter-parent</artifactId> <groupId>org.springframework.boot</groupId> <version>2.6.2</version> </parent> <name>blog-parent</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <!-- springboot开发web的起步依赖--> <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> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.6.3</version> </plugin> </plugins> </pluginManagement> </build> </project>
-
编写启动类
package com.lys; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
-
编写一个Controller测试一下
package com.lys; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class DemoController { @RequestMapping("/hello") public String hello() { return "hello!!!!"; } }
-
启动项目,访问lcoalhost下的/hello
通过以上,搭建起步springboot就好了!!!
【踩坑提示】
package com.lys;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class Test1 {
@Test
void demo() {
System.out.println(2);
}
}
我在启动上面的代码时报下面的错:
经过排查,导致上述的问题的原因是【启动类所在的包和单元测试的包不在同一级根目录下】,如下:
将上面的包名改成一致,即【org】改成【com】,就不会再报错了