警告的原因是:静态字段不支持自动注释

时间:2014-04-11 13:56:59

标签: java spring autowired

据我所知,使用@Autowired无法对static字段使用Spring注释。当我运行我的JBoss服务器时,一切正常,但我看不到任何警告:

Autowired annotation is not supported on static fields: private static ...

我不经常使用这个注释(在这个项目中我还没有使用它)但也许我的一些同事发现它更有用。

所以,我采取了以下警告之一:

Autowired annotation is not supported on static fields: private static java.lang.String com.my.package.MyClass.myVariable

我打开了这个课,里面是:

@Value("${params.myvariable}")
private static String myVariable;
    // getter
    // setter

我打开了config.xml

<bean id="myid" class="com.my.package.MyClass">
    <property name="myVariable" value="${params.myvariable}" />
</bean>

作为最后一件事,我在项目的EclipseAutowired字符串中进行了搜索。结果集的大小为 0

所以我的问题是,警告的原因是什么:

Autowired annotation is not supported on static fields

在这种情况下?

提前谢谢

1 个答案:

答案 0 :(得分:7)

这个

<bean id="myid" class="com.my.package.MyClass">
    <property name="myVariable" value="${params.myvariable}" />
</bean>

表示您有一个班级MyClass,例如

class MyClass {
    ...
    public void setMyVariable(String value) {
        ...
    }
}

根据您的描述,...可以替换为您的static字段

private static String myVariable;
// in setter method
myVariable = value;

这是自动装配static字段的解决方法,通常无法完成。 Spring适用于bean(实例),而不适用于类。