要通過注解讀取Spring Boot的YML配置,請按照以下步驟操作:
pom.xml
文件中添加以下依賴: <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency><dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</dependency>
src/main/resources
目錄下創(chuàng)建一個名為application.yml
或application.properties
的配置文件,并添加需要的配置信息。例如:app:
name: MyApplication
version: 1.0.0
@Configuration
和@ConfigurationProperties
注解標記這個類。例如:import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private String name;
private String version;
// Getters and setters
}
@Autowired
注解將AppConfig
類注入到相應的類中。例如:import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Autowired
private AppConfig appConfig;
@GetMapping("/config")
public String getConfig() {
return "Name: " + appConfig.getName() + ", Version: " + appConfig.getVersion();
}
}
現(xiàn)在,當你訪問/config
端點時,將會看到從YML配置文件中讀取的配置信息。