一、SpringBoot入门程序
Spring Quickstart Guide:https://spring.io/quickstart
1.根据需求在线生成自己的工程(选择需要的功能)
2.将生成的Demo下载、导入到Intellij IDEA
3.将官方Guide第二步的代码复制到SpringbootDemoApplication.java中(注意类上添加@RestController注解,否则访问时404)
4.点击绿色三角形运行程序(端口问题会导致启动失败,见PS)
5.浏览器访问http://localhost:8888/hello?name=你的名字即可
PS:因为我装了Oracle数据库,抢占了8080端口,所以项目启动失败.
解决方法:application.properties文件中添加一句话server.port=8888,重新运行程序即可
代码参考:
SpringbootDemoApplication.java
package com.lanying.springboot_demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication // 标记该类为SpringBoot引导类
@RestController // 相当于@Controller + @ResponseBody
public class SpringbootDemoApplication {
public static void main(String[] args) {
// run方法中传入引导类的字节码对象
SpringApplication.run(SpringbootDemoApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
QuickController.java
package com.lanying.springboot_demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class QuickController {
@RequestMapping("/quick")
@ResponseBody // 将返回内容直接写入响应体,避免视图解析器添加前后缀
public String quick(){
return "SpringBoot OK!";
}
}
pom.xml文件参考
<?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.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lanying</groupId>
<artifactId>springboot_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>