Injecting a Value in a Static Field in Spring – 在Spring的静态字段中注入一个值

最后修改: 2020年 3月 7日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll see how we can inject a value from a Java properties file to a static field with Spring.

在本教程中,我们将看到如何使用Spring将Java属性文件中的一个值注入到静态字段。

2. Problem

2 问题

To begin with, let’s imagine that we set a property to a properties file:

首先,让我们想象一下,我们将一个属性设置到一个属性文件中。

name = Inject a value to a static field

Afterward, we want to inject its value to an instance variable.

之后,我们要把它的值注入到一个实例变量中。

That usually can be done by using the @Value annotation on an instance field:

通常可以通过在实例字段上使用@Value注释来实现。

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

However, when we try to apply it to a static field, we’ll find that it will still be null:

然而,当我们试图将它应用于一个静态字段时,我们会发现它仍然是null

@Value("${name}")
private static String NAME_NULL;

That’s because Spring doesn’t support @Value on static fields.

这是因为Spring不支持静态字段的@Value

Now, truthfully, this is an odd position for our code to be in, and we ought to first consider refactoring. But, let’s see how we can make this work.

现在,说实话,我们的代码处于这样一个奇怪的位置,我们应该首先考虑重构。但是,让我们来看看我们如何能让它发挥作用。

3. Solution

3.解决办法

First, let’s declare the static variable we want to inject NAME_STATIC.

首先,让我们声明我们要注入的静态变量NAME_STATIC

Afterward, we’ll create a setter method, called setNameStatic and annotate it with the @Value annotation:

之后,我们将创建一个setter方法,叫做setNameStatic,并用@Value注解来注释它。

@RestController
public class PropertyController {

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

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

Let’s try and make sense of what’s happening above.

让我们试着把上面发生的事情弄明白。

First, PropertyController, which is a RestController, is being initialized by Spring.

首先,PropertyController是一个RestController,正在被Spring初始化。

Afterward, Spring searches for the Value annotated fields and methods.

之后,Spring搜索Value注释的字段和方法。

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it’s handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

Spring使用依赖注入来填充特定的值,当它找到@Value 注释时。然而,我们并没有将该值交给实例变量,而是将其交给了隐式设置器。

4. Conclusion

4.总结

In this short tutorial, we’ve looked at how to inject a value from a properties file into a static variable. This is a route we can consider when our attempts to refactor fail.

在这个简短的教程中,我们研究了如何将属性文件中的一个值注入静态变量中。当我们尝试重构失败时,这是一条我们可以考虑的途径。

As always, the code is available over on GitHub.

像往常一样,代码可在GitHub上获得