为什么组合 @component 和 bean 失败?

Why it failed when combining @component and bean?

我正在尝试使用@component 和普通bean。下面是我的代码:

MainApp.java

package com.company;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      TextEditor te = (TextEditor) context.getBean("textEditor");

      te.spellCheck();
   }
}

SpellChecker.java

package com.company;

public class SpellChecker {
   public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
   }

   public void checkSpelling(){
      System.out.println("Inside checkSpelling." );
   }
}

TextEditor.java

package com.company;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class TextEditor {
   @Autowired
   private SpellChecker spellChecker;
   @Autowired
   @Qualifier("region")
   private String region;

   public TextEditor() {
      System.out.println("I am in " + region );
   }

   public SpellChecker getSpellChecker( ){
      return spellChecker;
   }

   public void spellCheck(){
      spellChecker.checkSpelling();
   }
}

Beans.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:annotation-config/>
   <context:component-scan base-package="com.company" />

   <bean id="spellChecker" class="SpellChecker" />

   <bean id="region" class="java.lang.String">
      <constructor-arg value="Vancouver" />
   </bean>

</beans>

然而,当我运行这段代码时,它给出了错误信息:

Cannot find class [SpellChecker] for bean with name 'spellChecker' defined in class path resource

当我为 SpellChecker 删除 Beans.xml 中的 bean 并将 @component 标记为它时。然后它起作用了(但是,区域字符串仍然是空的)。

所以我的问题是:为什么我们不能在 @Component class 中自动装配一个 bean?

Spring Integration无关,请正确选择问题标签。

你的问题是 SpellCheckercom.company 包中,但是 <bean class=""> 确实需要完全限定的 class 名称来定义正确的 class实例化。

base-package="com.company" 正是为了 @Component 扫描,但这完全与常规 <bean> 定义无关。

通过使用完全限定的 class 名称,它应该可以工作... <bean id="spellChecker" class="com.company.SpellChecker" />