Spring - autowired fields are null

2019-08-13 23:42发布

I faced a problem with Spring Framework: @Autowired are null, but Spring doesn't throw any exceptions, and I can't understand, why are these fields null.

I have a class:

package com.processing.gates;

public class Main {

    private final ApplicationContext context = Context.getContext();

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

    //...
}

And for example I have the following class:

package com.processing.gates.comission;

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

Here is my Spring configuration 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>

When I try to write in xml:

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

and get it from code:

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

it works fine. But @Autowired doesn't work. How can I fix this? Thanks!

1条回答
Anthone
2楼-- · 2019-08-14 00:37

Let Spring manage the bean by either declaring a Main bean in the application context file or by using the @Component annotation as you've already done for CalculatorChooser

<bean id="mainBean" class="com.processing.gates.Main"/>
查看更多
登录 后发表回答