Spring Boot提供了多种方式来读取配置文件的值,包拥有以下几种常用的方式:
- 使用
@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 doSomething() { System.out.println("my.property value is: " + myProperty); } }
在上面的例子中,通过@Value("${my.property}")
注解来读取配置文件中my.property
的值。
- 使用
@ConfigurationProperties
注解读取配置值:
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; } }
在上面的例子中,通过@ConfigurationProperties(prefix = "my")
注解来读取配置文件中以my
开头的属性,并将其映射到MyProperties
类中。
- 使用
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 doSomething() { String propertyValue = https://www.yisu.com/ask/env.getProperty("my.property", "default value"); System.out.println("my.property value is: " + propertyValue); } }
在上面的例子中,通过Environment
类的getProperty
方法来读取配置文件中my.property
的值。
以上是一些常用的读取配置文件值的方式,根据具体情况选择适合自己的方式。