Spring-boot 最小demo

时间:2021-07-06 08:48:14

POM 文件,注意红色部分:

<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>spring-boot-starter-data-mongodb</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
     <!-- SpringBoot打包插件 ( 打包好的Jar可以直接用“java -jar YOUR_JAR.jar”命令启动 ) -->
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

程序入口:

package com.cui;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
} @Override
public void run(String... args) throws Exception {
System.out.println("Spring加载完后执行的逻辑,可以直接使用Spring上下文,以及依赖注入@Autowired");
}
}

最简单的Web应用 (然而这并不是重点,仅仅是POM中spring-boot-starter-web组建的简单示例, 更多组件参考 http://www.mvnrepository.com/search?q=spring-boot-starter- ):

package com.cui;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping("/{id}")
public String view(@PathVariable("id") Long id) {
return id + " ~~";
}
}