【问题标题】:Spring component-scan not working弹簧组件扫描不起作用
【发布时间】:2012-09-07 17:10:14
【问题描述】:

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>

我有这样的课:

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 的引用是非空的。

但是,myBean 不会被注入并且始终为 null(myBean 本身被初始化为单例,它只是没有被注入)。我还需要做什么才能使其正常工作?如果我将测试类添加到 applicationContext.xml 一切正常。我的猜测是 Test 只是没有被 Spring 初始化,因此没有连接。

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

【问题讨论】:

    标签: java spring


    【解决方案1】:

    我不相信你可以直接用 Spring 注入静态字段。见this

    【讨论】:

      【解决方案2】:

      Spring 的理念是初始化和配置您的类(即对象)的实例。实际上,这意味着 @Autowired 不能应用于 static 字段,因为静态字段不属于任何实例(并且您的访问器方法也不应该是 static)。

      【讨论】:

      • 好的,我应该提供更多上下文,我需要它们是静态的,因为它们被称为自定义 JSP 函数。我更新了我的描述。不过谢谢,这是我没有的一条信息:)
      • 像这样工作 :) 现在我需要做的就是将类的一个实例存储为单例,并通过它访问 Spring 注入的对象。
      猜你喜欢
      • 2015-12-12
      • 2017-09-02
      • 1970-01-01
      • 2011-07-13
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2011-01-02
      相关资源
      最近更新 更多