Spring组件扫描不起作用

Tim*_*Tim 2 java spring

Spring组件扫描似乎没有用.我使用的是Spring 3.1和tomcat 7.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>
Run Code Online (Sandbox Code Playgroud)

我有一个这样的课:

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; }
}
Run Code Online (Sandbox Code Playgroud)

我原以为Spring会在启动web应用程序时初始化Test,而myBean会自动注入,所以如果我调用任何(静态)Test方法,我对myBean的引用都是空的.

但是,myBean不会被注入并且始终为null(myBean本身被初始化为singleton,它不会被注入).要做到这一点,我还需要做些什么?如果我将Test-class添加到applicationContext.xml,一切正常.我的猜测是Spring没有初始化Test,因此没有连线.

更新: 我需要能够从静态上下文访问自动连接字段(此类的方法被称为JSP函数),因此它必须是静态的.

axt*_*avt 7

Spring的想法是初始化和配置类的实例(即对象).实际上,这意味着@Autowired无法应用于static字段,因为静态字段不属于任何实例(并且您的存取方法也不应该static如此).