Spring-自动装配字段为空 [英] Spring - autowired fields are null
问题描述
我在使用Spring Framework时遇到了一个问题:@Autowired
为null,但是Spring不会引发任何异常,而且我也不明白,为什么这些字段为null.
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.
我有一堂课:
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:
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>
当我尝试用xml编写时:
When I try to write in xml:
<bean id="calculator" class="com.processing.gates.comission.CalculatorChooser"/>
并从代码中获取它:
CalculatorChooser cc = (CalculatorChooser)Context.getContext().getBean("calculator");
它工作正常.但是@Autowired不起作用.我怎样才能解决这个问题?谢谢!
it works fine. But @Autowired doesn't work. How can I fix this? Thanks!
推荐答案
让Spring通过在应用程序上下文文件中声明Main
bean或使用@Component
批注来管理bean. CalculatorChooser
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"/>
这篇关于Spring-自动装配字段为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!