Spring - autowired fields are null

给你一囗甜甜゛ 提交于 2019-12-11 09:06:10

问题


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:


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"/>


来源:https://stackoverflow.com/questions/30279039/spring-autowired-fields-are-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!