溫馨提示×

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

小云
174
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女