简体   繁体   English

如何在我的普通代码中使用 application.yml 文件中的变量?

[英]How do I use a variable from an application.yml file in my normal code?

For example, let's say that in my yml file I had a variable called indicator.例如,假设在我的 yml 文件中有一个名为 indicator 的变量。 And based on what the indicator variable's value was I want the code to do something different.并且基于指标变量的值是什么,我希望代码做一些不同的事情。 How would I access the yml variable in the regular code and use it accordingly?我将如何访问常规代码中的 yml 变量并相应地使用它?

You can use this:你可以使用这个:

@Value("${your.path.yml.string}")
private String x;

YML: YML:

your:
  path:
    yml:
      string: hello

x will be "hello" x 将是“你好”

  1. You need to use Spring Expression Language which says we should write it as您需要使用 Spring 表达式语言,它说我们应该把它写成
    @Value("${spring.application.name}") 
    private String appName;
  1. For Default value if key is not present in yaml/yml or properties file如果 yaml/yml 或属性文件中不存在键,则为默认值
    @Value("${spring.application.name: defaultValue}") 
    private String appName;
  1. The last way you can fetch value is using environment object最后一种获取价值的方法是使用环境 object
    @Autowired  
    private Environment environment;
       
    String appName = environment.get("spring.application.name");

You can add @Value annotation to any field in your beans.您可以将@Value注释添加到 bean 中的任何字段。

@Value("$(path.to.your.variable)")
String myString;

Works with constructors as well.也适用于构造函数。

public MyClass(@Value("$(path.to.your.variable)") String myString) {

You can use @Value on fields or parameters to assign the property to some variable.您可以在字段或参数上使用@Value将属性分配给某个变量。

Property example:属性示例:

@Value("${indicator}")
private String indicator

Parameter example:参数示例:

private void someMethod(@Value("${indicator}") String indicator) {
    ...
}

Then you can use indicator as you want.然后,您可以根据需要使用指标

Note: the class where you use @Value should be a Spring Component注意:您使用@Value的 class 应该是 Spring 组件

With Spring-Boot, you have the file application.yml automatically provided for you.使用 Spring-Boot,您可以自动为您提供文件application.yml What you can do is adding a property in this file, for instance:您可以做的是在此文件中添加一个属性,例如:

my.properties: someValue

Then, in one of your Spring Bean (either define with @Component or @Bean ) you can retrieve this value using the annotation @Value .然后,在您的 Spring Bean 之一(使用@Component@Bean定义)中,您可以使用注释@Value检索此值。 Then, do whatever you want with this variable.然后,对这个变量做任何你想做的事情。

For instance:例如:

@Component
public class MyClass {

    @Value("${my.properties"}
    private String myProp; // will get "someValue" injected.

    ...


    // Just use it in a method
    public boolean myMethod() {
        if(myProp.equals("someValue") {
            // do something
        } else {
            // do something else
        } 
    }
}

The best way to do this is not to have a tight coupling between Spring and your "normal" code at all, but instead to use the normal Java features like constructors along with Spring @Bean methods:最好的方法是不要在 Spring 和您的“正常”代码之间建立紧密耦合,而是使用正常的 Java 功能,如构造函数以及@Bean方法:

class MyService {
    final String indicatorName;

    MyService(String indicatorName) {
        this.indicatorName = indicatorName;
    }
}

... in your configuration class... ...在您的配置中 class...

@Bean
MyService myService(@Value("indicator.name") String indicatorName) {
    return new MyService(indicatorName);
}

Two notes for Spring Boot specifically: Spring Boot 的两个注意事项:

  • The @ConfigurationProperties feature allows you to map properties onto structured Java data classes and is typically cleaner than using @Value by hand. @ConfigurationProperties功能允许您将 map 属性添加到结构化的 Java 数据类上,并且通常比手动使用@Value更干净。
  • Always namespace properties that you define yourself to avoid future collisions with other libraries, so instead of indicator.name use company.project.indicator.name .始终使用您自己定义的命名空间属性以避免将来与其他库发生冲突,因此使用company.project.indicator.name代替indicator.name I recommend looking at DataSourceProperties in Boot to see an example of how to set all this up.我建议查看 Boot 中的DataSourceProperties以查看如何设置所有这些的示例。

More broadly, though, when you say that you want the code to "do something different", it sounds like the better option might be to have different classes that get activated under different circumstances.但是,更广泛地说,当您说您希望代码“做一些不同的事情”时,听起来更好的选择可能是让不同的类在不同的情况下被激活。 Both Spring profiles and Spring Boot auto-configuration help to do this. Spring 配置文件和 Spring 引导自动配置都有助于执行此操作。

The problem statement can be re-defined as Configuration Management in Java.问题陈述可以重新定义为Java中的配置管理。

You should have a component like ConfigManager that gets instantiated as part of your application start up.你应该有一个像 ConfigManager 这样的组件,它在你的应用程序启动时被实例化。 That component will read a properties file, a yaml in your use case.该组件将读取一个属性文件,即您的用例中的 yaml。 Subsequent app logic will fetch these values from the ConfigManager exposed as simple key/value pairs.后续应用逻辑将从公开为简单键/值对的 ConfigManager 中获取这些值。

All that is left for you to identify how to read and parse values from yaml file.剩下的就是让您确定如何从 yaml 文件中读取和解析值。 This is already answered here: Parse a YAML file这已经在这里得到了回答: Parse a YAML file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用我的子模块中的 application.yml 文件? - How to use application.yml file from my sub modules? 如何让 Spring 在 Docker 容器中使用 application.yml 文件? - How do I get Spring to use an application.yml file in a Docker container? 在 springboot 应用程序中,如果我需要在代码中使用它们,如何从 application.yml 中读取值 - In a springboot application, how can I read values form application.yml, if I need to use them in my code 如何使用Spring Boot从application.yml读取变量并在Kotlin测试中使用它 - How to read variable from application.yml with spring boot and use it in kotlin test 如何在 mySpringBoot application.yml 中配置 HikariCP? - How do I configure HikariCP in mySpringBoot application.yml? java 8 Springboot 如何在注释中使用 application.yml 文件中的属性? - java 8 Springboot How to use properties from application.yml file in annotations? 如何从 application.yml 文件注入属性? - How to inject properties from application.yml file? 如何在 Spring 2.7.2 中从 application.yml 读取配置值 - How do I read config values from application.yml in Spring 2.7.2 Spring 引导:配置未正确加载我的密码变量来自 application.yml - Spring Boot: configuration does not load correctly my password variable from application.yml 我可以使用在 javax.validation.constraints.Max 中的 application.yml 中定义的自动装配变量吗? - Can I use an autowired variable that's defined in application.yml in javax.validation.constraints.Max?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM