SpringBoot是SpringMVC的升级版,SpringBoot的特点:
application.properties文件配置: server.port = 8080端口配置
server.context-path = /girl URL前缀 application.yml文件配置:
server:
port: 8081
context-path: /girl 建议使用yml文件来配置 属性配置: @Value:单属性配置 @Value("${cupSize}")
private String cupSize;//通过一个注解,把配置文件里的属性注入进来 配置文件里是这样的:
server:
port: 8080
girl:
cupSize: B
age: 18
类里面是这样的:
@Component
@ConfigurationProperties(prefix = "girl")//可以把配置文件里相应前缀下的属性全部注入进来
public class GirlProperties{ private String cupSize;
private Integer age; getset方法略....
} 实体类初始化属性注入时,需要添加两个注解 @Component//把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>
Controller层的注解使用:
匹配多个路径:
@RequestMapping(value={“hello”,“hi”} ,method=RequestMethod.GET) RestController = Controller + ResponseBody @PathVariable("id")获取路url中的数据
@RequestMapping(value="hello/{id}" ,method=RequestMethod.GET)
使用方法:public String say(@PathVariable("id")Integer id){} @RequestParam("id")获取请求的参数值
@RequestMapping(value="hello" ,method=RequestMethod.GET)
使用方法:public String say(@RequestParam("id")Integer id){}
value:请求的属性
required:是否必须如传参 defaultValue:默认值
@RequestMapping(value="hello" ,method=RequestMethod.GET)
使用方法:public String say(@RequestParam(value="id",required=false,defaultValue="0")Integer id){} @GetMapping 组合注解 使用方法:
@GetMapping(value="/say")意思就是get方式的请求映射 还有@PostMapping(value="/say")
数据库操作:
实体类设计:(注意要生成一个无参构造器,听说不这样的话就会报错)
数据库配置:
ddl-auto: create 每次都会创建表 如果表存在就会先drop再create
ddl-auto: update 表不存在就create 表存在就update
ddl-auto: validate 验证表结构
ddl-auto: create-drop 程序结束后会把表drop掉
查询所有和新增:
private GirlRepository girlRepository; //查询所有女生
@GetMapping(value="/girls")
public List<Girl> girlList(){ return girlRepository.findAll();
} //添加一个女生
@PostMapping("/girls")
public girl girlAdd(@RequestParam("cupSize")String cupSize,
@RequestParam("age") Integer age){
Girl girl=new Girl();
girl.setCupSize(cupSize);
girl.setAge(age);
return girlRepository.save(girl);
} //查询一个女生
@GetMapping("/girls/{id}")
public girl girlFindOne(@PathVariable("id")Integer id) {
return girlRepository.findOne(id);
} //更新
//添加一个女生
@PutMapping("/girls/{id}")
public girl girlAdd (@PathVariable("id") Integer id,
@RequestParam("cupSize")String cupSize,
@RequestParam("age") Integer age){
Girl girl=new Girl();
girl.setId(id);
girl.setCupSize(cupSize);
girl.setAge(age);
return girlRepository.save(girl);
} //删除
@DeleteMapping(value="/girls/{id}")
public void girlDelete(@PathVariable("id") Integer id){
girlRespository.delete(id);
}
数据库操作Jpa实现增删改查,接口方法名有讲究
实务操作 只需要加上注解@Transactiona