当自动装配存在于不同包中的字段时,我无法自动装配。
我的代码看起来像这样
注入课程
package com.vmware.vchs.networkservice.extensions.http
@Component
public class HttpServiceClient implements ContextAware
{
@Autowired
JMXAgent jMXAgent;
....
};
注入课程
package com.vmware.vchs.networkservice.monitoring;
@Component
public class JMXAgent {
};
我的组件扫描xml文件如下所示
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:bean="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
<context:property-placeholder
location="classpath:environment.properties"
ignore-unresolvable="false"/>
<bean:component-scan base-package="com.vmware.vchs.networkservice"/>
</beans>
错误是
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Err
or creating bean with name 'httpServiceClient': Injection of autowired dependencies fai
led; nested exception is org.springframework.beans.factory.BeanCreationException: Could
not autowire field: com.vmware.vchs.networkservice.monitoring.JMXAgent com.vmware.vchs.
networkservice.extensions.http.HttpServiceClient.jmxAgent; nested exception is org.spri
ngframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [co
m.vmware.vchs.networkservice.monitoring.JMXAgent] found for dependency: expected at lea
st 1 bean which qualifies as autowire candidate for this dependency. Dependency annotat
ions: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
答案 0 :(得分:0)
为了Automatically detecting classes and registering bean definitions我通常使用context
而不是bean
:
<?xml version="1.0" encoding="UTF-8"?>
<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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.example"/>
</beans>
<强>更新强>
<context:component-scan base-package="com.vmware.vchs.networkservice"/>
<context:component-scan base-package="com.vmware.vchs.networkservice.extensions.http"/>
答案 1 :(得分:0)
我的程序正在从不同的xml读取。这就是找不到bean的原因