@Autowired我遇到了一个很大的问题,那就是异常返回
bean的初始化失败; 嵌套异常是org.springframework.beans.factory.BeanInitializationException:bean'A'需要属性'serviceFactory'
以下是所有内容的简要说明(我使用的是Spring 3.2,并且我已将所有jar放在正确的位置WEB-INF/lib).
applicationContext.xml中
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="com.sc" />
<!-- Comment out - we are going to use @Component @Autowired - 2014-01-07
<bean id="A" class="com.sc.A">
<property name="serviceFactory" ref="serviceFactoryBean" />
</bean>
-->
<bean id="serviceFactoryBean" class="com.sc.ServiceFactory" autowire="byName" />
</beans>
Run Code Online (Sandbox Code Playgroud)
com.sc.A类的内容
@Component
public class A
{
private Logger logger = Logger.getLogger(A.class);
// @Autowired -- 2014-01-07 comment out as not need it since annotation in setter below
// @Qualifier("serviceFactoryBean")
private ServiceFactory serviceFactory;
public A()
{ }
@Autowired // add 2014-01-07
@Required
public void setServiceFactory(ServiceFactory serviceFactory)
{
this.serviceFactory = serviceFactory;
}
public boolean checkSomething()
{
if(this.serviceFactory == null)
logger.error("serviceFactory is null. Autowired failed");
// do something
}
} // end of class A
Run Code Online (Sandbox Code Playgroud)
类com.sc.ServiceFactory的内容
// @Component -- comment out 2014-01-07
public class ServiceFactory
{
// do whatever
}
Run Code Online (Sandbox Code Playgroud)
然后我编译了这些类并在jetty中运行它,当jetty上升时,它总是抛出很长的例外
org.springframework.beans.factory.BeanCreationException:创建在URL中定义名称为"A"的bean时出错... bean的初始化失败; 嵌套异常是org.springframework.beans.factory.BeanInitializationException:bean'A'需要属性'serviceFactory'
我尝试了很多有和没有注释的组合无济于事.面对这个错误是非常令人沮丧的.
请帮忙
在你的问题中有一些错误(或者说是误解).
使用当前上下文,您将为每个A和声明两个bean定义ServiceFactory.一个隐含地来自@Component注释,<component-scan>另一个来自显式<bean>声明.选择其中一个或者您可能会发现自己处于Spring不知道使用哪个位置.
有了上述内容,Spring会A因为它的@Component注释而尝试生成一个bean,并@Required在setServiceFactory()方法上查看,但不知道如何处理它.@Required的贾瓦多克说
将方法(通常是JavaBean setter方法)标记为"required":即,必须将setter方法配置为使用值依赖注入.
但在你的情况下,事实并非如此.添加@Autowired到它.
@Required
@Autowired
public void setServiceFactory(ServiceFactory serviceFactory) {
this.serviceFactory = serviceFactory;
}
Run Code Online (Sandbox Code Playgroud)
现在Spring将知道如何处理该方法,即.注入一个ServiceFactory豆子.
| 归档时间: |
|
| 查看次数: |
2009 次 |
| 最近记录: |