我在读取我的环境变量和同时满足 SonarLint(检测并修复质量问题)时遇到问题.. 这样它就不起作用我的变量是空的
private String accessKey;
@Value("${bws.access.key}")
public void setAccessKey(String ak){
accessKey=ak;
}
将方法更改为静态(如 sonarLint 推荐的那样)对变量连续 null 不起作用
private static String accessKey;
@Value("${bws.access.key}")
public static void setAccessKey(String ak){
accessKey=ak;
}
我发现唯一可行的方法是将实例变量标记为静态但不将方法标记为静态
private static String accessKey;
@Value("${bws.access.key}")
public void setAccessKey(String ak){
accessKey=ak;
}
但是有sonarLint指出了问题 实例方法不应写入“静态”字段
这不是让我越过边界的环境变量不正确吗?
最佳答案
您可以使用以下代码:
一个配置类(用 @Component
注释以便被 Spring 获取)它将保存来自属性文件的值,您可以在其中绑定(bind) bws.access 的值.key
直接指向一个属性。如果您需要 accessKey
的访问器方法,您可以创建它们(setAccessKey
和 getAccessKey
)
@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;
}
}
有关更多详细信息,请查看此 GitHub sample project .
我测试过
(编辑)如何在 Controller 中使用它:
一个选项(还有其他选项)可以是为 Controller 声明一个构造函数(我们称之为 SampleController
)并在其中请求一个 ConfigClass
类型的参数。现在我们将相同类型的 Controller 属性 (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
}
}
现在,Spring Boot 将尝试在 ConfigClass
类型的应用程序中找到一个组件(任何类型),因为我们已经定义了一个组件,它会自动将它注入(inject)我们的 Controller 中。通过这种方式,您可以将参数 Controller 属性 config
设置为 configClass
中收到的值以供以后使用。
为了测试它,您可以请求 url test
。您将看到输出将是 anotherValue
。因此我们可以得出结论,依赖注入(inject)机制成功找到了 ConfigClass
的实例,并且 ConfigClass#getAccessKey
方法正常工作。
关于java - 获取环境变量并通过 SonarLint 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51024223/