Spring - 自动装配字段为空

Spring - autowired fields are null

我遇到了 Spring 框架的问题:@Autowired 为空,但 Spring 没有抛出任何异常,我不明白,为什么这些字段为空.

我有一个 class:

package com.processing.gates;

public class Main {

    private final ApplicationContext context = Context.getContext();

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

    //...
}

例如我有以下 class:

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 不起作用。我怎样才能解决这个问题?谢谢!

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

<bean id="mainBean" class="com.processing.gates.Main"/>