温馨提示×

Spring Boot使用yml格式进行配置的方法

小云
106
2023-08-16 15:15:00
栏目: 编程语言

Spring Boot使用yml格式进行配置的方法分为以下几个步骤:

  1. 在项目的src/main/resources目录下创建一个名为application.yml的文件。

  2. application.yml文件中使用yml格式进行配置,例如:

server:
port: 8080
servlet:
context-path: /api
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: password
jpa:
hibernate:
ddl-auto: update
show-sql: true
logging:
level:
root: INFO
com.example: DEBUG
  1. 在Spring Boot的启动类上使用注解@EnableAutoConfiguration@SpringBootApplication
@SpringBootApplication
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
  1. 在需要读取配置的地方使用注解@Value@ConfigurationProperties来注入配置属性。
@RestController
public class ExampleController {
@Value("${server.port}")
private int serverPort;
@Value("${server.servlet.context-path}")
private String contextPath;
@GetMapping("/info")
public String getInfo() {
return "Server Port: " + serverPort + ", Context Path: " + contextPath;
}
}

这样,就可以使用yml格式进行配置了。在项目启动时,Spring Boot会自动读取application.yml文件中的配置并注入到对应的属性中。

0