1.@SpringBootApplication
启动项目注释
2.@RestController
@Controller处理http请求(必须配合模版使用)
@RestController = @Controller + @ResponseBody
3.@RequestMapping
@RequestMapping 支持多个url访问,下面的代码我访问/hello和/hi都进入welcome方法
@RequestMapping(value = {"/hello", "/hi"}, method = RequestMethod.GET)
public String welcome(){
return "hollo spring boot";
}
@RequestMapping(value单个url访问
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String welcome(){
return "hollo spring boot";
}
method 可以设置请求方式,不设置是任何请求都可以
常用的就是post和get两种
method = RequestMethod.GET
method = RequestMethod.POST
RequestMapping也有组合注解比如
@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里面被调用)