Spring Boot可以通过在application.yml文件中定义属性来读取属性。可以使用@Value注解或@ConfigurationProperties注解来读取yml文件中的属性。
@Value注解读取属性:import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic class MyComponent { @Value("${myproperty}") private String myProperty; public void doSomething() { System.out.println("My Property: " + myProperty); }}使用@ConfigurationProperties注解读取属性:首先在application.yml文件中定义属性:my: property: value然后创建一个配置类来读取属性值:
import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;@Component@ConfigurationProperties(prefix = "my")public class MyProperties { private String property; public String getProperty() { return property; } public void setProperty(String property) { this.property = property; }}在其他类中可以直接注入这个配置类,并使用属性值:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Componentpublic class MyComponent { @Autowired private MyProperties myProperties; public void doSomething() { System.out.println("My Property: " + myProperties.getProperty()); }}通过以上方法,Spring Boot就可以读取并使用yml文件中的属性值。


