SpringBoot入门案例


入门案例

1.新建Spring Initializr项目,pom文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>

    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.4.10
         
    
    com.emhum
    demo
    0.0.1-SNAPSHOT
    demo
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

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


  • spring-boot-starter-parent 是 SpringBoot 项目的父级依赖,它被称为 SpringBoot 的版本仲裁中心,可以对项目内的部分常用依赖进行统一管理。
  • spring-boot-starter-web 提供了嵌入的 Servlet 容器以及 SpringMVC 的依赖,并为 Spring MVC 提供了大量自动配置,可以适用于大多数 Web 开发场景。

2.主程序类:

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}
  • @SpringBootApplication:该注解表示这是一个SpringBoot的应用

3.编写controller:

//@Controller
//@ResponseBody
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(){
        return "Hello SpringBoot";
    }
}

4.启动项目,访问:http://localhost:8080/hello
将会看到如下输出:

Hello SpringBoot

创建可执行的jar包

在pom.xml添加打包插件:


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

使用mvn命令或者在IDEA执行package。打包后的jar文件位于target目录下。

使用命令直接运行jar文件即可:

java -jar demo-0.0.1-SNAPSHOT.jar