Java 在 Spring 中注入静态常量的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2763279/
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-08-13 12:34:53  来源:igfitidea点击:

Injecting values for static constants in Spring

javaspringstaticpropertiescode-injection

提问by Shyam

In one of my classes there is a public static Stringmember and I need set this value in the applicationContext.xml! That is, is it possible for us to inject a value for this static property?

在我的一个班级中有一个public static String成员,我需要在 applicationContext.xml! 也就是说,我们可以为这个静态属性注入一个值吗?

回答by Espen

No, it's not possible to inject a value to a static field from your XML context.

不,不可能从 XML 上下文向静态字段注入值。

If you can modify the class, you have the following simple choices:

如果您可以修改类,您有以下简单的选择:

  • remove the static modifier and add @Inject/@Autowire above the field
  • add a constructor/setter/init method.
  • 删除静态修饰符并在字段上方添加@Inject/@Autowire
  • 添加构造函数/setter/init 方法。

Else, you can do it with Spring's Java configuration support.

否则,您可以使用 Spring 的 Java 配置支持来实现。

An example:

一个例子:

The Demo class with the static field and a JUnit method that asserts that the Spring container injects the wanted value into the static field:

带有静态字段和 JUnit 方法的 Demo 类断言 Spring 容器将所需的值注入静态字段:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("test-context.xml")
public class Demo {

    public static String fieldOne;

    @Test
    public void testStaticField() {
        assertEquals("test", fieldOne);     
    }
}

Add the context namespace to your applicationContext and component-scan element:

将上下文命名空间添加到您的 applicationContext 和 component-scan 元素:

<context:component-scan base-package="com.example" />

Add your bean with the static field like the this:

添加带有静态字段的 bean,如下所示:

@Configuration
public class JavaConfig {

    @Bean
    public Demo demo() {
        Demo.fieldOne = "test";

        return new Demo();
    }
}

In this case, the JavaConfig class must be in the com.example package as declared in the component-scan element.

在这种情况下,JavaConfig 类必须在组件扫描元素中声明的 com.example 包中。