SpringBoot快速入门
一.项目配置
-
注解
@Value
@Component
@ConfigurationProperties
-
配置文件案例
1
2
3
4//application.yml
spring:
profiles:
active: dev1
2
3
4
5
6
7
8
9
10//application-dev.yml
server:
port: 8081
servlet:
context-path: /luckymoney
limit:
minMoney: 0.1
maxMoney: 9999
description: 最少要发${limit.minMoney}元,最多可发${limit.maxMoney}元
二.Controller的使用
-
Controller:处理http请求
-
RestController:返回json(相当于@ResponseBody配合@Controller)
-
RequestMapping:配置url映射(可传入数组,Crtl+P查看)
-
PathVariable:获取url中的数据
1
2
3
4
5
6// url:/say/100
public String say( Integer id){
// return "说明:"+limitConfig.getDescription();
return "id:"+id;
} -
RequestParam:获取请求参数的值
1
2
3
4
5
6
7// url:/say?id=100
//@RequestParam(value = "id", required = false, defaultValue = "0") 非必须传值
public String say( Integer id){
//return "说明:"+limitConfig.getDescription();
return "id:"+id;
}
三.操作数据库
-
引入依赖
1
2
3
4
5
6
7
8<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency> -
配置文件(以Hibernate为例)
1
2
3
4
5
6
7
8
9
10spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/luckymoney
username: root
password:
jpa:
hibernate:
ddl-auto: update
show-sql: true -
事务
1
2
3
4
5
6
7
8
9
10
11
12
13
14//事务:指数据库事务,同时创建两个红包,保证两个都创建或都不创建
//注意:数据库要改为InnoDB引擎
public void createTwo(){
Luckymoney luckymoney1 = new Luckymoney();
luckymoney1.setProducer("Bill");
luckymoney1.setMoney(new BigDecimal("520"));
repository.save(luckymoney1);
Luckymoney luckymoney2 = new Luckymoney();
luckymoney2.setProducer("Peter");
luckymoney2.setMoney(new BigDecimal("1314"));
repository.save(luckymoney2);
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 515code-实验室!
评论