springboot

springboot怎么获取application.yml的值

小亿
170
2024-08-11 15:32:34
栏目: 编程语言

在Spring Boot项目中,可以通过使用@Value注解来获取application.yml中的值。

首先,在Spring Boot的配置类中使用@PropertySource注解来指定application.yml的位置,例如:

@Configuration
@PropertySource("classpath:application.yml")
public class AppConfig {
}

然后在需要获取值的地方,使用@Value注解来注入对应的值,例如:

@Component
public class MyComponent {

    @Value("${my.property}")
    private String myProperty;
    
    public String getMyProperty() {
        return myProperty;
    }
}

application.yml中定义的my.property属性可以通过@Value注解注入到MyComponent组件中。

0
看了该问题的人还看了