一个Java要实现SpringBoot项目,需要继承SpringBoot Parent项目,将我们的项目作为SpringBoot Parent的子项目。
有3种方法来创建一个SpringBoot项目,我们先来看第一种方法:基于一个maven项目来创建SpringBoot项目。
1)File-》New-> Project…-》选择meven-》选择“maven-archetype-quickstart”,点击next
2)输入项目名称,点击next
3)设置项目基本信息,包括group、artifact、package等,点击Finish
4)此时项目结构已经自动生成了,要让项目成为SpringBoot项目,还需要两步
<1>在pom文件中加入以下代码:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<2>在项目源码中自动生成了入口类,添加注解:@SpringBootApplication
此时原本普通的maven项目就变成了SpringBoot项目。
编写代码:
/**
* Hello world!
*
*/
@SpringBootApplication
@RestController
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
运行代码,控制台输出如下:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.5.4)
2022-07-28 15:10:53.397 INFO 19312 --- [ main] org.itzhimei.App : Starting App using Java 1.8.0_181 on DESKTOP-UCGATI0 with PID 19312 (SpringBootFromMaven\target\classes started by itzhimei in SpringBootFromMaven)
2022-07-28 15:10:53.398 INFO 19312 --- [ main] org.itzhimei.App : No active profile set, falling back to default profiles: default
2022-07-28 15:10:54.084 INFO 19312 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-07-28 15:10:54.091 INFO 19312 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-07-28 15:10:54.091 INFO 19312 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.52]
2022-07-28 15:10:54.166 INFO 19312 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-07-28 15:10:54.166 INFO 19312 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 714 ms
2022-07-28 15:10:54.397 INFO 19312 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-07-28 15:10:54.403 INFO 19312 --- [ main] org.itzhimei.App : Started App in 1.456 seconds (JVM running for 2.308)
测试代码:
浏览器打开:http://localhost:8080/hello
输出结果:
Hello World!