获取环境变量并通过SonarLint的正确方法

Man*_*ini 5 java spring-boot

我在读取环境变量并同时满足 SonarLint(检测和修复质量问题)时遇到问题..这样它就不起作用了,我的变量为 null

 private String accessKey;
 @Value("${bws.access.key}")
public void setAccessKey(String ak){
    accessKey=ak;
}
Run Code Online (Sandbox Code Playgroud)

将方法更改为静态(按照 sonarLint 的建议)不会对变量连续 null 起作用

private static String accessKey;
  @Value("${bws.access.key}")
public static void setAccessKey(String ak){
    accessKey=ak;
}
Run Code Online (Sandbox Code Playgroud)

我发现唯一有效的方法是将实例变量标记为静态,但不将方法标记为静态

private static String accessKey;
  @Value("${bws.access.key}")
public void setAccessKey(String ak){
    accessKey=ak;
}
Run Code Online (Sandbox Code Playgroud)

但 sonarLint 指出了问题 实例方法不应写入“静态”字段

难道我跨越边界获取环境变量的方式不正确吗?

lea*_*iro 3

您可以使用以下代码:

一个配置类(注释为 ,@Component以便由 Spring 获取),它将保存来自属性文件的值,您可以在其中将 的值bws.access.key直接绑定到属性。如果您需要访问器方法,accessKey您只需创建它们(setAccessKeygetAccessKey

@Component
public class ConfigClass {

    // @Value("${bws.access.key:<no-value>}")  // <- you can use it this way if you want a default value if the property is not found
    @Value("${bws.access.key}")                // <- Notice how the property is being bind here and not upon the method `setAccessKey`
    private String accessKey;

    // optional, in case you need to change the value of `accessKey` later
    public void setAccessKey(String ak){
        this.accessKey = ak;
    }

    public String getAccessKey() {
        return this.accessKey;
    }

}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看此GitHub 示例项目

我测试了这个

  • IntelliJ IDEA 2018.1.5(终极版),内部版本#IU-181.5281.24
  • 声纳林特在此输入图像描述

编辑)如何在控制器中使用它

一个选项(还有其他选项)可以是为控制器声明一个构造函数(我们称之为)并请求其中的SampleController类型参数。ConfigClass现在我们将相同类型的控制器属性 ( config) 设置为作为参数接收的值,如下所示:

@RestController
public class SampleController {

    private final ConfigClass config;

    public SampleController(ConfigClass configClass) { // <- request the object of type ConfigClass
        this.config = configClass; // <- set the value for later usage
    }

    @RequestMapping(value = "test")
    public String test() {
        return config.getAccessKey();  // <- use the object of type ConfigClass
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,Spring Boot 将尝试在类型的应用程序中找到一个组件(任何类型)ConfigClass,并且由于我们已经定义了一个组件,因此它会自动将其注入到我们的控制器中。通过这种方式,您可以将参数控制器属性设置config为收到的值configClass以供以后使用。

为了测试它,您可以请求 url test。您将看到输出为anotherValue. 因此我们可以得出结论,依赖注入机制成功找到了 的实例,ConfigClass并且该方法ConfigClass#getAccessKey工作正常。