例如:读取该yaml
my.property=someValue
1. 使用@Value
注解读取配置
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
@Value("${my.property}")
private String myProperty;
public void printProperty() {
System.out.println("Property value: " + myProperty);
}
}
2. 使用@ConfigurationProperties
注解读取配置
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "my")
public class MyConfig {
private String property;
// getters and setters
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
}
3. 通过Environment
对象读取配置
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
@Autowired
private Environment env;
public void printProperty() {
String myProperty = env.getProperty("my.property");
System.out.println("Property value: " + myProperty);
}
}