簡介:本章提供了springboot簡單例子,主要包含以下內容
1.pom.xml依賴資源
2.springboot配置
3.web應用spring mvc
環境:
IDEA15+
JDK1.8+
Maven3+
一、pom.xml依賴資源
由於功能相對簡單,這裡引用的第三方資源文件相對較少
spring-boot-starter:約定大於配置,目的解放勞動力.
spring-boot-starter-tomcat: 主要內嵌servlet容器(tomcat)
spring-webmvc: spring核心jar及mvc功能
具體pom.xml配置如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-webmvc.version}</version>
</dependency>
</dependencies>
由於dependency具有依賴傳遞性,整個依賴樹如下:
另外,在執行的過程中需要依賴於spring-boot-maven-plugin
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot-maven-plugin.version}</version>
</plugin>
</plugins>
</build>
pom.xml相關的配置基本上就這麼多
二、springboot配置
springboot基於“約定大於配置”的思想,同時提供了個性化定制的方案或擴展的入口,application.properties, 這裡可以用屬性鍵值對的方式進行定制,比如:
logging.level.: DEBUG #日志默認level: INFO server.port: 1010 #tomcat 訪問端口設置為1010, 默認8080
springboot執行入口:Chapter01Application.java
@SpringBootApplication
public class Chapter01Application {
public static void main(String[] args)throws Exception{
SpringApplication.run(Chapter01Application.class);
}
}
非常簡單,與一般java類沒有太大的區別,多了一個注解@SpringBootApplication, 另外提供了main方法,至此一個簡單springboot環境搭建好了
三、web應用springboot
傳統配置springmvc 時需要自定義Servlet指定DispatcherServlet,配置映射規則url-pattern。這裡由於使用了springboot,我們不需要進行額外的配置。直接創建Controller即可
@Controller
public class Chapter01Controller {
@Autowired
private HelloService helloService;
@RequestMapping("/")
@ResponseBody
public String helloWord(){
return helloService.getHelloMessage();
}
}
當我們訪問localhost:1010/時,會執行helloWord方法
啟動工程,在IDEA環境下會檢測Springboot環境,自動創建了Run/Debug Configurations。這裡會指定Main class: com.shujushow.chapter01.Chapter01Application。 我們只需要Shift+F10即可執行,啟動完成後,我們可以訪問localhost:1010