Spring - 自动连接的字段为空

时间:2015-05-16 18:03:49

标签: java spring dependency-injection inversion-of-control autowired

我遇到了Spring Framework的问题:@Autowired为null,但Spring没有抛出任何异常,我无法理解,为什么这些字段为空。

我有一个班级:

package com.processing.gates;

public class Main {

    private final ApplicationContext context = Context.getContext();

    @Autowired private PaymentGateFactory paymentGateFactory;
    @Autowired private CalculatorChooser calculatorChooser;

    //...
}

例如,我有以下课程:

package com.processing.gates.comission;

@Component
public class CalculatorChooser {
    //...
}

这是我的Spring配置xml:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/jdbc 
        http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">

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


    <bean id="logPath" class="java.lang.String"> <!-- путь к папке с логами -->
        <constructor-arg value="/home/yoba/NetBeansProjects/processing/gates/log/"/>
    </bean>
    <!-- ... -->
</beans>

当我尝试用xml编写时:

<bean id="calculator" class="com.processing.gates.comission.CalculatorChooser"/>

从代码中获取:

CalculatorChooser cc = (CalculatorChooser)Context.getContext().getBean("calculator");

它工作正常。但@Autowired不起作用。我怎样才能解决这个问题?谢谢!

1 个答案:

答案 0 :(得分:2)

让Spring通过在应用程序上下文文件中声明Main bean或使用@Component注释来管理bean,就像你已经为CalculatorChooser

做的那样
<bean id="mainBean" class="com.processing.gates.Main"/>