早就开始了解到Spring Boot,但是一直没有自己动手学习。最近开始学习,就将学习过程记录下来和大家一起分享,希望对和我一样刚刚起步的小伙伴们有帮助。
新建一个maven项目。
新建完成后进行如下配置。
maven配置,pom文件:
<?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>SpringBootLearning</groupId>
<artifactId>SpringBootLearning</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-releases</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>
Application类
package com.seawater;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Created by zhouhs on 2016/12/29.
*/
@EnableAutoConfiguration
@ComponentScan
@Configuration
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class,args);
}
}
- EnableAutoConfiguration 这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring
- ComponentScan扫描Spring组件
- Configuration配置组件
最后就是我们的ResetController
package com.seawater.controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by zhouhs on 2016/12/29.
*/
@RestController
@RequestMapping("/sea")
public class HelloWorldController{
@RequestMapping(value = "/{name}",method = RequestMethod.GET)
public String Hello(@PathVariable("name") String name){
return "Hello , "+ name;
}
}
启动项目,访问 http://localhost:8081/sea/seawater。
我们的项目就完成了。
注意:我们的项目结构一定要对哦。否则是可能会出现Whitelabel Error Page错误。找了很久。最后发现是文件结构错了,正确的结果如下:
这是官网的例子。
附上官网地址http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-structuring-your-code。
到这里这个项目才算真正完成,如有不正之处,还请指教。
源码地址(项目中的源码可能会更多哦,需要自己找到对应源码)