【发布时间】:2015-05-20 11:23:39
【问题描述】:
我阅读了有关自动装配的概念并尝试在我的项目中使用它。我想要的只是为特定类创建一个实例,并且可以与所有具有自动装配的类一起使用。
我在 dispatcher-servlet.xml
中定义了一个 bean<bean id="modifyService"
class="com.xyz.service.ModifyPreferencesService"/>
没有定义范围,所以它将是单例的。 现在我在两个类中使用它。
class ABCEvaluationService{
@Autowired
ArrayList listIncident;
//This class is instantiating IncidentFactory with new keyword in a method
**//Methods using listIncident - getting empty list here**
}
class IncidentFactory{
**@Autowired
List listIncident
@Autowired
ModifyPreferencesService modifyService;**
//This class creates Incident Objects and add it to the listIncident.
**//Uses modifyService class objects - but I am getting null here**
}
问题是我可以在第一堂课中使用它,但在第二堂课中它给了我 NullPointerException。 其他 bean 也在发生同样的事情。 我在做什么这个错了。这不是自动装配的目的吗?请解释一下..我正在学习Spring,不想学习错误的概念。
完整的dispatcher-servlet.xml是(我不能真正复制粘贴..所以可能会出现语法错误。如果有请忽略):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:component-scan base-package="mypack" />
<mvc:annotation-driven/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/ABCReportForm"/>
<bean class="com.xyz.interceptor.ValueStreamInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<mvc:default-servlet-handler/>
<mvc:resources location="/resources/" mapping="/resources/**"/>
<bean id="validator"
class="com.xyz.validator.ABCValidator"/>
<bean id="modifyService"
class="com.xyz.service.ModifyPreferencesService"/>
<bean id="abcService"
class="com.xyz.service.ABCEvaluationService"/>
<bean id="listIncident"
class="java.utilArrayList"/>
//Code for InternalResourceViewer
</beans>
谢谢
【问题讨论】:
-
这两个类在哪些包中?你是怎么配置
<context:annotation-config/>和<context:component-scan base-package=...的 -
是的,我已经配置了 xml 文件。它一直在工作,直到我只有一堂课可以使用 bean/list。在第二次使用中,我得到了例外。这两个类都在不同的包中。
-
你能展示你完整的xml文件吗
-
是的..我会在问题中添加..
-
@King 是
A和B类属于您的工作代码吗?如果是这样,他们在哪里配置为 spring bean?
标签: java spring dependency-injection javabeans autowired