java 静态函数中@Value 注释的替代方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6897201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:49:22  来源:igfitidea点击:

An alternative to @Value annotation in static function

javaspringstaticannotations

提问by Sanghyun Lee

It's not possible to use @Valueon a static variable.

不能@Value在静态变量上使用。

@Value("${some.value}")
static private int someValue;

static public void useValue() {
    System.out.println(someValue);
}

When I do this, 0is printed. So what is a good alternative to this?

当我这样做时,0打印出来。那么有什么好的替代方法呢?

回答by Ralph

Spring inject noting in static field (by default).

Spring 在静态字段中注入注释(默认情况下)。

So you have two alternatives:

所以你有两种选择:

  • (the better one) make the field non static
  • (the ugly hack) add an none static setter which writes in the static field, and add the @Valueannotation to the setter.
  • (更好的)使字段非静态
  • (丑陋的黑客)添加一个写入静态字段的非静态 setter,并将@Value注释添加到 setter。


回答by membersound

Use this simple trick to achieve what you want (way better than having the value injected into non-static setters and writing so a static field - as suggested in the accepted answer):

使用这个简单的技巧来实现你想要的(比将值注入非静态 setter 并编写静态字段更好 - 正如接受的答案中所建议的那样):

@Service
public class ConfigUtil {
    public static ConfigUtil INSTANCE;

    @Value("${some.value})
    private String value;

    @PostConstruct
    public void init() {
        INSTANCE = this;        
    }

    public String getValue() {
        return value;
    }
}

Use like:

像这样使用:

ConfigUtil.INSTANCE.getValue();

ConfigUtil.INSTANCE.getValue();

回答by Florian Sager

To prevent ever repeating injections of the same value making a field non-staticin a class that gets instantiated very often, I preferred to create a simple Singleton ConfigUtil as a workaround:

为了防止重复注入相同的值使经常实例化的类中的字段变得非静态,我更喜欢创建一个简单的 Singleton ConfigUtil 作为解决方法:

package de.agitos.app.util;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;

/**
 * Helper class to get injected configuration values from static methods
 * 
 * @author Florian Sager
 *
 */

@Configurable
public class ConfigUtil {

    private static ConfigUtil instance = new ConfigUtil();

    public static ConfigUtil getInstance() {
        return instance;
    }

    private @Value("${my.value1}") Integer value1;

    public Integer getValue1() {
        return value1;
    }
}

Inside the class I tried to inject the value first as a static Integer:

在类中,我尝试首先将值作为静态整数注入:

private static Integer value1 = ConfigUtil.getInstance().getValue1();