【问题标题】:Autowiring is not working when configured through XML通过 XML 配置时自动装配不起作用
【发布时间】:2013-09-09 20:04:40
【问题描述】:
class ConfigurationDetails {
    private @Resource String esHostURL;
    private @Resource int maxMessageCounter;
    private @Resource String queueName;
   // Assume : This class has all getter and setter methods and a default constructor
}

另一个类

public class SpringMessageListener implements MessageListener {
    @Resource ConfigurationDetails configDetails; // With getter and setter method for this
............
..........

在我的 XML 中

<bean id="aListener" class="com.vzw.es.cosumer.SpringMessageListener" autowire="byName"/>
<bean id="configDetails" class="com.vzw.es.pojo.ConfigurationDetails"  autowire="byName">
    <property name="esHostURL" value="http://obsgracstg-db0.odc.vzwcorp.com:9200"/>
    <property name="maxMessageCounter" value="500"/>
    <property name="queueName" value="ES_queue"/>
</bean>

现在,当我调试代码并看到 SpringMessageListerner 类中的 configDetails 显示为 null 时,id 为 configDetails 的 bean 没有获得自动装配的含义。但是当我明确执行 appContext.getBean("configDetails") 时,它给了我非空对象。

为什么自动装配不起作用?我错过了什么吗?

【问题讨论】:

  • 向我们展示您的component-scan
  • 我的 XML 中没有任何组件扫描元素
  • 在这里添加我的整个 XML
  • 我无法在此处添加整个 XML,但对于我项目中的另一个 bean,它运行良好,即 RabbitAdmin

标签: spring autowired


【解决方案1】:

默认情况下,Spring 不会查找 @Autowired@Resource@Inject 注释来自动装配您的 bean。你需要告诉它去寻找他们

<context:component-scan base-package="com.yourpackage.some" />
// or, in this case, <context:annotation-config />

这样,Spring 将扫描包中的类并注入存在@Autowired@Resource 的bean。

不要忘记添加命名空间声明

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

更重要的是

class ConfigurationDetails {
    private @Resource String esHostURL;
    private @Resource int maxMessageCounter;
    private @Resource String queueName;
   // Assume : This class has all getter and setter methods and a default constructor
}

虽然您可以自动装配 Stringint 类型,但这通常被认为是不好的做法。而是在此处删除 @Resource 注释并为每个字段添加 getter 和 setter。

&lt;bean&gt; 声明中的 property 元素负责设置这些字段。

【讨论】:

  • 现在它给了我异常:创建名为“configDetails”的bean时出错:资源依赖注入失败;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到类型为 [java.lang.String] 的合格 bean:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。
  • @JavaCoder 很好,我们取得了进展。删除ConfigurationDetails 字段上的@Resource 注释,并为每个字段添加getter/setter。
  • 它现在可以工作了,非常感谢您的帮助。我还有一个快速的问题,如何将 XML 中的值设置为不同对象的属性,例如
  • 我想得到上面的 name 属性bean 并将其设置为另一个 beans 属性值,例如 但它没有给我实际值。任何帮助表示赞赏
  • @JavaCoder 欢迎您。看看答案here
猜你喜欢
  • 2018-09-18
  • 1970-01-01
  • 2014-09-01
  • 2017-01-19
  • 1970-01-01
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
  • 2019-09-27
相关资源
最近更新 更多