2

Springコンポーネントスキャンが機能していないようです。Spring3.1とtomcat7.0を使用しています。

これは私のapplicationContext.xmlがどのように見えるかです:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 
            http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">

    <context:annotation-config/> 
    <context:component-scan base-package="com.abc"/>

    <bean id="myBean" class="com.efg.test.MyBean" />
</beans>

私はこのようなクラスを持っています:

package com.abc.test

@Component
class Test {
    @Autowired
    private static MyBean myBean;

    public static MyBean getMyBean() { return myBean; }
    public static void setMyBean(MyBean bean) { myBean = bean; }
}

TestはWebアプリケーションの起動時にSpringによって初期化され、myBeanが自動的に挿入されることを期待していたので、Testの(静的)メソッドを呼び出すと、myBeanへのnull以外の参照があります。

ただし、myBeanは注入されず、常にnullになります(myBean自体はシングルトンとして初期化され、注入されないだけです)。これを機能させるには、他に何をする必要がありますか?TestクラスをapplicationContext.xmlに追加すると、すべてが機能します。私の推測では、TestはSpringによって初期化されていないため、有線ではありません。

更新: 静的コンテキスト(このクラスのメソッドはJSP関数と呼ばれます)からautowiredフィールドにアクセスできる必要があるため、静的である必要があります。

4

2 に答える 2

7

Springの考え方は、クラスのインスタンス(つまりオブジェクト)を初期化して構成することです。実際には、静的フィールドはどのインスタンスにも属していないため、フィールドに@Autowired適用できないことを意味しstaticます(また、アクセサメソッドも属してはなりませんstatic)。

于 2012-09-14T14:17:39.963 に答える
1

Springで静的フィールドを直接注入できるとは思いません。これを参照してください。

于 2012-09-14T14:20:03.830 に答える