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

huangapple go评论89阅读模式
英文:

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

问题

例如,假设在我的yml文件中有一个名为"indicator"的变量。根据"indicator"变量的值,我想让代码执行不同的操作。我该如何在常规代码中访问yml变量并相应地使用它?

英文:

For example, let's say that in my yml file I had a variable called 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?

答案1

得分: 8

你可以使用以下代码:

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

YML 文件内容如下:

your:
  path:
    yml:
      string: hello

x 的值将是 "hello"。

英文:

You can use this:

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

YML:

your:
  path:
    yml:
      string: hello

x will be "hello"

答案2

得分: 4

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

答案3

得分: 1

你可以在你的bean中的任何字段上添加@Value注解。

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

也可以在构造函数中使用。

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

You can add @Value annotation to any field in your beans.

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

Works with constructors as well.

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

答案4

得分: 1

你可以在字段或参数上使用@Value来将属性分配给某个变量。

属性示例:

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

参数示例:

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

然后你可以按需使用indicator

注意:使用@Value的类应该是一个Spring组件。

英文:

You can use @Value on fields or parameters to assign the property to some variable.

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

答案5

得分: 1

使用Spring Boot,你会自动获得application.yml文件。你可以在这个文件中添加一个属性,例如:

my.properties: someValue

然后,在你的一个Spring Bean中(可以使用@Component@Bean定义),你可以使用注解@Value来获取这个值。然后,你可以对这个变量进行任何你想要的操作。

例如:

@Component
public class MyClass {

    @Value("${my.properties}")
    private String myProp; // 将会注入 "someValue"。

    ...

    // 只需在一个方法中使用它
    public boolean myMethod() {
        if(myProp.equals("someValue")) {
            // 做某些操作
        } else {
            // 做其他操作
        } 
    }
}
英文:

With Spring-Boot, you have the file application.yml automatically provided for you. 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. 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
        } 
    }
}

答案6

得分: 0

这样做的最佳方式不是在Spring和您的“普通”代码之间紧密耦合,而是使用普通的Java功能,如构造函数以及Spring的@Bean方法:

class MyService {
    final String indicatorName;

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

... 在您的配置类中...

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

特别针对Spring Boot的两个注意事项:

  • @ConfigurationProperties功能允许您将属性映射到结构化的Java数据类,通常比手动使用@Value更清晰。
  • 始终为自定义定义的属性添加命名空间,以避免将来与其他库发生冲突,因此不要使用indicator.name,而要使用company.project.indicator.name。我建议查看Spring Boot中的DataSourceProperties,以查看如何设置所有这些内容的示例。

然而,更广泛地说,当您说希望代码“做一些不同的事情”时,听起来更好的选项可能是在不同情况下激活_不同的类。Spring配置文件和Spring Boot自动配置都有助于实现这一点。

英文:

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:

class MyService {
    final String indicatorName;

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

... in your configuration class...

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

Two notes for Spring Boot specifically:

  • The @ConfigurationProperties feature allows you to map properties onto structured Java data classes and is typically cleaner than using @Value by hand.
  • Always namespace properties that you define yourself to avoid future collisions with other libraries, so instead of indicator.name use company.project.indicator.name. I recommend looking at DataSourceProperties in Boot to see an example of how to set all this up.

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.

答案7

得分: -2

问题陈述可以重新定义为Java中的配置管理。

您应该有一个名为ConfigManager的组件,它在应用程序启动时被实例化。该组件将读取一个属性文件,对于您的用例来说是一个yaml文件。随后的应用逻辑将从ConfigManager中获取这些值,以简单的键/值对的形式暴露出来。

剩下的就是您如何识别如何从yaml文件中读取和解析值。这已经在这里得到了解答:
https://stackoverflow.com/questions/25796637/parse-a-yaml-file

英文:

The problem statement can be re-defined as Configuration Management in Java.

You should have a component like ConfigManager that gets instantiated as part of your application start up. That component will read a properties file, a yaml in your use case. Subsequent app logic will fetch these values from the ConfigManager exposed as simple key/value pairs.

All that is left for you to identify how to read and parse values from yaml file. This is already answered here:
https://stackoverflow.com/questions/25796637/parse-a-yaml-file

huangapple
  • 本文由 发表于 2020年7月29日 23:48:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63157446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定