1 springboot的启动方式:
(1) 在idea中直接运行Application;
(2) 进入工程目录下,通过mvn spring-boot:run 命令启动
(3) 在target目录下 通过 java -jar 跟上对应的 jar包名字来启动,
比如 java -jar springBoot-1.0-SNAPSHOT.jar
2 springboot中属性配置
@Value配置的使用
cupSize: B
age: 18
content: "cupSize: ${cupSize},age: ${age}" //在配置里面再使用配置
在controller中通过 @Value("${cupSize}")
@Value("${age}")
@Value("${content}") 注解来注入进去
3 把配置写到一个类去
@ConfigurationProperties注解表示是配置;
@Component注解用来表示bean;;
类中定义属性,prefix = "girl"表示配置文件girl的配置;
在配置文件中配置girl
girl:
name: B
age: 15
@Component
@ConfigurationProperties(prefix = "girl")
public class GirlProperties {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
4 多个配置文件(可以解决生产环境、调试环境对配置属性的不同需求)
比如 配置文件为application.yml
复制两份,一份命名为application-dev.yml
server:
port: 8081
girl:
name: F
age: 15
另一份配置为 application-prod.yml
server:
port: 8082
girl:
name: B
age: 15
想使用哪一个配置文件只需要在application.yml中指定,比如使用prod。
spring:
profiles:
active: prod
java -jar的启动方式可以加参数,指定配置文件:
java -jar java -jar springBoot-1.0-SNAPSHOT.jar --spring.profiles.active=prod
5 controller的使用
@PathVariable 获取url中的变量
localhost:8081/hello/2 则返回值 id:2
@RequestMapping(value = "/hello/{id}")
public String sayHi(@PathVariable("id")Integer id){
return "id: "+id;
}
//required=false,表示不要求必传,defaultValue设置默认值
localhost:8081/hello?id=3
@GetMapping(value = "/hello")
public String sayHi(@RequesParam(value = "id",required = false,defaultValue = "0")Integer id){
return "id: "+id;
}
6 springboot jpa操作数据库
对应的配置文件
spring:
profiles:
active: prod
datasource:
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root123
url: jdbc:mysql://localhost:3306/dbgirl
jpa:
hibernate:
ddl-auto: update
show-sql: true
创建实体,由于配置了hibernate,在应用启动的时候框架会自动去数据库中创建对应的表。
@Entity
public class Girl {
@Id
@GeneratedValue
private Integer id;
private Integer age;
private String name;
private double money;
//省略构造函数和getter,setter
}
//Girl是类名,Integer是 数据库 id的类型
定义一个接口 public interface GirlRepository extends JpaRepository<Girl,Integer> {
}
@RestController
public class GirlController {
@Autowired
private GirlRepository girlRepository;
@GetMapping(value = "/girls")
public List<Girl> getGirlList(){
return girlRepository.findAll();
}
}
@PutMapping 中put的数据格式为 x-www-form-urlencoded
如果想通过其他属性来查询,可以在接口中进行扩展,
如通过年龄查询
public interface GirlRepository extends JpaRepository<Girl,Integer> {
public List<Girl> findByAge(Integer age);
}
7 事务管理
插入的时候,在方法上加注解 @Transactional ,保证同时满足条件;
查询的时候不需要事务管理