Spring Boot使用yml格式进行配置的方法分为以下几个步骤:
-
在项目的
src/main/resources
目录下创建一个名为application.yml
的文件。 -
在
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
- 在Spring Boot的启动类上使用注解
@EnableAutoConfiguration
和@SpringBootApplication
。
@SpringBootApplication @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
- 在需要读取配置的地方使用注解
@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
文件中的配置并注入到对应的属性中。