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里面被调用)

相关文章
相关标签/搜索