SpringBoot註解解釋

1.@SpringBootApplication

啓動項目註釋java

2.@RestController

@Controller處理http請求(必須配合模版使用)程序員

@RestController = @Controller + @ResponseBodyspring

3.@RequestMapping

@RequestMapping 支持多個url訪問,下面的代碼我訪問/hello和/hi都進入welcome方法數據庫

@RequestMapping(value = {"/hello", "/hi"}, method = RequestMethod.GET)
	public String welcome(){
		return "hollo spring boot";
	}

@RequestMapping(value單個url訪問app

@RequestMapping(value = "/hello", method = RequestMethod.GET)
	public String welcome(){
		return "hollo spring boot";
	}

method 能夠設置請求方式,不設置是任何請求均可以post

經常使用的就是post和get兩種ui

method = RequestMethod.GETthis

method = RequestMethod.POSTurl

RequestMapping也有組合註解好比spa

    @GetMapping和@PostMapping等等

下面說下接收參數:

第一種:

請求:www.xxx.com/say/45

@RequestMapping(value="/say/{id}", method= RequestMethod.GET)
public String test(@PathVariable("id")Integer id) {
	return "id=" + id;
}

第二種:

請求:www.xxx.com/say?id=5

@RequestMapping(value="/say", method= RequestMethod.GET)
public String test(@RequestParam("id")Integer myId) {
	return "id=" + myId;
}

而且支持默認值

請求:www.xxx.com/say 或者 www.xxx.com/say?id=9

@RequestMapping(value="/say", method= RequestMethod.GET)
public String test(@RequestParam(value="id", required = false, defaultValue = "0")Integer myId) {
	return "id=" + myId;
}

說明:

required:參數是否必傳

defaultValue:默認值,必須是字符串

 

4.@ConfigurationProperties

application.properties配置文件內容:

people.username=馬少
people.sex=男
people.age=29
people.job=程序員

直接去配置文件變量:

@Value("$配置文件的變量名")
private 類型 變量名

另外一種寫法:

新建對象PeopleProperties

@Component  這個註解是爲了讓別的地方能注入

@Component
@ConfigurationProperties(prefix = "people")
public class PeopleProperties {
	
	private String  username;
	
	private String  age;
	
	private String  job;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getJob() {
		return job;
	}

	public void setJob(String job) {
		this.job = job;
	}
}

5.@Transactional

@Transactional
public test(){
	//插入數據庫操做第一次
	//插入數據庫操做第二次
}

說明:

@Transactional這個註解就是事物,若是你想第一次插入數據庫和第二次插入數據庫  要麼都成功要麼都失敗,就要用到這個註解(事物不能在相同的service裏面被調用)

相關文章
相關標籤/搜索