2012-09-14 91 views
2

Spring組件掃描似乎不起作用。我使用Spring 3.1和Tomcat 7.0。Spring組件掃描不起作用

這是我的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> 

我有這樣一個類:我本來以爲測試將被Spring的web應用的啓動初始化

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; } 
} 

並且myBean將被自動注入,所以如果我調用測試的任何(靜態)方法,那麼對myBean有一個非空引用。

但是,myBean沒有被注入並且始終爲空(myBean本身被初始化爲singleton,它只是沒有被注入)。我還需要做些什麼才能做到這一點?如果我將Test-class添加到applicationContext.xml中,那麼一切正常。我的猜測是Test並未被Spring初始化,因此沒有連線。

更新: 我需要能夠從靜態上下文訪問自動裝配Autowired場(本類的方法被稱爲一個JSP的功能),因此它必須是靜態的。

回答

7

Spring的想法是它初始化和配置你的類(即對象)的實例。實際上,這意味着@Autowired不能應用於static字段,因爲靜態字段不屬於任何實例(並且您的訪問器方法也不應該是static)。

+0

好的,我應該給更多的上下文,我需要它們是靜態的,因爲它們被稱爲自定義JSP函數。我更新了我的描述。不過謝謝你,這是我沒有的信息:) – Tim

+0

像這樣工作:)現在我需要做的就是將類的一個實例存儲爲singleton,並通過它訪問Spring注入的對象。 – Tim

1

我不相信你可以直接用Spring注入靜態字段。見this