在Spring Boot中,可以通過@Value注解、Environment接口、@ConfigurationProperties注解等方式來讀取配置文件。
@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(myProperty);
}
}
上述代碼中,@Value("${my.property}")注解用于將配置文件中my.property的值注入到myProperty屬性中。
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 myProperty = env.getProperty("my.property");
System.out.println(myProperty);
}
}
上述代碼中,通過env.getProperty("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為前綴的配置文件屬性值注入到同名的屬性中。在application.properties配置文件中,可以通過my.property來設置property屬性的值。
注意:在使用@ConfigurationProperties注解時,需要在主類上添加@EnableConfigurationProperties(MyProperties.class)注解來啟用配置屬性的注入。
除了這些方法,還可以使用@PropertySource注解、@Configuration注解等方式來讀取配置文件。具體使用哪種方式,取決于你的需求和個人偏好。