在Spring Boot中,可以使用@Value注解来获取yml中的变量。首先,在需要获取变量的类中使用@Value注解,然后在注解中指定要获取的变量的属性名,如下所示:
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic class MyComponent { @Value("${my.variable}") private String myVariable; public String getMyVariable() { return myVariable; }}在上面的例子中,@Value("${my.variable}")注解指定了要获取的yml配置文件中的my.variable属性的值,并将其注入到myVariable变量中。然后可以通过调用getMyVariable()方法来获取这个值。
另外,如果需要在整个应用程序中获取yml中的变量,也可以通过@Value注解注入Environment对象来实现,如下所示:
import org.springframework.beans.factory.annotation.Value;import org.springframework.core.env.Environment;import org.springframework.stereotype.Component;@Componentpublic class MyComponent { @Value("${my.variable}") private String myVariable; private final Environment env; public MyComponent(Environment env) { this.env = env; } public String getMyVariable() { return env.getProperty("my.variable"); }}在这个例子中,通过构造函数注入Environment对象,然后可以通过调用getProperty()方法来获取yml中的变量的值。


