我在读取环境变量并同时满足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指出了这个问题 实例方法不应写入“静态”字段
不是通过这种方法来获取环境变量而不是正确的边界吗?
答案 0 :(得分:2)
您可以使用以下代码:
一个配置类(用@Component
标注,以便被Spring拾取),它将保存来自属性文件的值,您可以在其中将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。
我用
进行了测试(编辑)如何在控制器中使用:
一个选择(还有其他选择)可能是为控制器声明一个构造函数(我们将其称为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
}
}
现在,Spring Boot将尝试在类型为ConfigClass
的应用程序中找到一个组件(任何类型),并且由于我们已经定义了一个组件,它将自动将其注入到控制器中。这样,您可以将参数控制器属性config
设置为configClass
中接收的值,以供以后使用。
为了对其进行测试,您可以请求URL test
。您将看到输出为anotherValue
。因此,我们可以得出结论,依赖注入机制已成功找到ConfigClass
的实例,并且方法ConfigClass#getAccessKey
可以正常工作。