springboot怎么读取yml文件属性

   2024-10-01 4400
核心提示:Spring Boot可以通过在application.yml文件中定义属性来读取属性。可以使用@Value注解或@ConfigurationProperties注解来读取yml

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文件中的属性值。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号