在此之前,給大家推薦幾個東西.
STS,Spring官方基於eclipse做的擴展ide.Spring官方背書.
第二個,lombok,註解生成get/set,構造以及基本方法的插件,"隱藏大量非業務代碼",可以讓我們的業務代碼變的更純淨,更加容易維護.
第三個,推薦一下JPA,現在也越來越流行.
總之呢,目的就是讓我們的代碼閱讀性更強,規範我們的開發.
下面編寫我們第一個Spring boot應用
先構建一個maven項目,在pom.xml文件中添加springboot web依賴
<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>com</groupId> <artifactId>SrpingBoot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>boot</name> <description>第一個SpringBoot應用</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
接下來我們新建一個springboot啓動類,用@SpringBootApplication標識它
package com; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
新建一個Controller類,提供網頁訪問接口,@RestController註解默認以json格式返回.
package com.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class Controller { @RequestMapping(name="/add" ,method=RequestMethod.GET) public Integer add(@RequestParam Integer a, @RequestParam Integer b) { return a+b; } }
運行Application類的main方法,我們第一個springboot 應用就創建成功了,是不是超級方便呢
接下來我們訪問以下localhost:8080/add?a=1&b=2看以下吧~