@SpringBootApplication
@SpringBootApplication是一個組合註解
其中包括@SpringBootConfiguration、@EnableAutoConfiguration、
和@ComponentScan註解。
@SpringBootConfiguration
繼承至@Configuration,此註釋表示當前類是配置類,並會將當前類中聲明
一個或者多個以@Bean註解標記的方法的實例納入到Spring容器中,實例名
就是方法名。
@EnableAutoConfiguration
此註解是SpringBoot自動進行配置的核心,通過此註解能將所有符合自動配置
條件的Bean的定義加載到spring容器中。
@ComponentScan
此註解會掃描當前包及其子包下被@Component,@Controller,@Service,@Re
pository等註解biao標記的類納入到spring容器中進行管理。
@Controller和RestController
@RestController是spring4之後加入的註解,原來在@Controller中返回jso
n需要@ResponseBody來配合,如果直接用@RestController替代@Controlle
r,默認返回json格式。而@Controller是用來創建處理http請求的對象,一般
結合@RequestMapping使用。
@ReuqestMapping
一個用來處理請求地址映射的註解,可以用於類或方法上。用於類上,表示類
中的所有響應請求都是該地址作爲父路徑。
@RestController
@RequestMapping ( "/test" )
public class HelloWorld {
@RequestMapping ( "/hello" )
public String hello ( ) {
return " hello world!" ;
}
}
常見屬性
value:指定請求的實際地址,指定的地址可以是URL模式。
method:指定請求的method類型,GET POST PUT DELETE等。
consumes:指定處理請求的提交內容類型。如application/json、text/html
params:指定request中必須包含某些參數值,才讓該方法處理。
headers:指定reuqest中必須包含某些指定的header值,才讓該方法處理請求。
@RequestBody和@ResponseBody
@ReuqestBody註解允許request的參數在請求體中,通常結合前段POST請求
進行前後端交互。
@ResponseBody註解是將java對象轉爲json格式的數據返回給前端。
@PathVariale
當使用@RequestMapping URL tempalte樣式映射的時候,即"/test/{Id}"
這時的Id可以通過@PathVariale註解綁定它傳過來的值到方法的參數上。
@RestController
@RequestMapping ( "/test/{Id}" )
public class TestParhVariable {
@RequestMapping ( "/hello/{personId}" )
public String hello ( @PathVariable String Id, @PathVariable String personId) {
return "接收到訪問路徑裏面的變量參數: Id=" + Id+ ", personId=" + personId;
}
}