controller
类前面需要加上@controller注解
RequestMapping("/boot/hello"):访问路径的注解, 方法名必须和路径名一致,即方法名为hello
@ResponceBody : 返回json的注解,加在方法返回参数前面
核心配置文件
.properties或者.yml(排版格式不一样,空格和换行方式)文件
配置举例:
server.port=8080:配置端口
server.context-path=/springbootdemo:配置访问的路径(/不能少)
多环境配置文件
有多个配置文件,在总配置文件中可以选择哪一个(比如测试和上线的配置文件不一样)
spring.profiles.active=dev
(假设有一个文件为application-dev.properties配置文件)
如果有配置既存在总配置文件,也存在其他配置文件,总配置的优先级更低,即优先使用引用的那个配置文件中的配置。
自定义配置文件
默认不存在的配置,可以自定义,
比如
boot.name=beijing
boot.location = haidian
要使用这种配置,需要自己读取,
- Value注解,
Value("${boot.name}")
private String name;
此种方式就可以将beijing注入到name中。 - ConfigurationProperties注解
SpringBoot下使用SpringMVC
- Controller注解
- RestController注解:controller + responcebody
- GetMapping注解:等于RequestMapping 和get方式请求的结合
即等价于RequestMapping("/boot/hello", method=RequestMethod.GET) - PostMapping, PutMapping, DeleteMapping
SpringBoot使用mybatis
添加mybatis的依赖(需要自己指定版本,父级中没有该依赖)以及mysql的依赖
增加配置如下:
mybatis.mapper-location=classpath:com/bupt/springboot/mapper/*.xml
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://10.3.8.211/databaseName?useUnicode=true&characteEncoding=utf8&useSSL=false
Mapper注解 或者 MapperScan(主类上添加,即Application类上添加)
三层,四个文件夹(与Application类同级目录)
controller springmvc的代码
mapper mybatis的接口和xml文件
service service层, 接口和impl Service注解, autowired自动注入
model 相关pojo, 比如学生类, 用户类
idea编辑器,会出现编译后,找不到xml等文件,需要在依赖中加入resource?,让xml文件编译进去
事务支持
入口类上添加EnableTransactionManagement注解开启事务支持
在对应的Service方法上添加@Transactional注解
restful风格
PathVariable注解
@RequestMapping("/boot/user/{id}/{name}")
public object user(@PathVariable("id") Integer id, @PathVariable("name") String name) {
......
}
热部署
热部署插件
引入依赖spring-boot-devtools
集成redis
加在redis依赖spring-boot-starter-data-redis
配置redis连接信息
spring.redis.host=10.3.8.211
spring.redis.port=
spring.redis.password=123456
springboot自动生成了Redis Template, 需要的时候可以直接使用,只需autowire注入即可
@Autowired
private RedisTemplate<object, object> redisTemplate; 范型只能是<String, String> 或者<object, object>
使用:
redisTemplate.opsForValue().get(key);
redisTemplate.opsForValue().set(key, value);