搭建一個簡單地本地后臺服務器
建立一個空項目
項目名稱
創(chuàng)建Module
相關(guān)名稱配置
相關(guān)依賴的勾選1
相關(guān)依賴的勾選2
創(chuàng)建一個contorller接口
- @RestController 標志這是一個控制器
- @ResponseBody 會包裝返回結(jié)果
- @RequestMapping 是匹配前臺請求路徑的
package com.demo.springboot.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
//公開一個方法hello
@ResponseBody
@RequestMapping("/hello")
public String hello(){
return "hello spring boot!!";
}
}
啟動服務器
- 測試
測試結(jié)果
1.下面是Spring最著名的一個功能 依賴注入
依賴注入
package com.demo.springboot.service;
import org.springframework.stereotype.Service;
@Service
public class HelloService {
public String sayHello(){
return "Hello this is Service";
}
}
依賴注入2
依賴注入3
結(jié)果
從main方法開始看,SpringApplication.run 傳進去了一個class對象,通過反射 拿到了類的Package(com.demo.springboot)阴汇,然后會掃描包下的所有類晌纫。拿到類的注解 @RestController @Component @Service刘莹,那么就會構(gòu)建這個類 newInstance罢艾,然后掃描類的所有字段,保護@Autowired 注入實例拄衰。
2.修改傳入?yún)?shù)
參數(shù)的傳入
測試結(jié)果
通過注釋設(shè)置默認值蛤奢,就算沒有輸入?yún)?shù)也會有磨人的值在其中返回
注釋設(shè)置默認值
結(jié)果
路徑變量來進行輸入?yún)?shù)的填寫
路徑變量
結(jié)果