刚学spring就遇到一个奇怪的问题,在网上找了半天也没解决。。
这是我的demo,一个接口两个bean实现,再选择注入到含有该接口的service,代码如下:
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> <bean id="springHello" class="com.spring.service.impl.SpringHello"></bean>
<bean id="mybatisHello" class="com.spring.service.impl.MybatisHello"></bean> <bean id="helloService" class="com.spring.service.HelloService"></bean></beans>
public class HelloService
{
//   ??? @Qualifier不起作用
@Autowired
@Qualifier("springHello")
Hello hello;

public HelloService()
{

}

//@Autowired

public HelloService(Hello hello){
this.hello = hello;
System.out.println("auto-write by constructor");
}

public Hello getHello()
{
return hello;
}

//@Autowired
public void setHello(Hello hello)
{
System.out.println("auto-write by type");
this.hello = hello;
}

}
如上,麻烦给看看哪有问题,感激不尽!

解决方案 »

  1.   

    @Qualifier()写在参数前面,指定要注入的值
    错误原因因该是:
    你要注入的是SpringHello Bean实例,但是却注入给了Hello类型的,所以出错。
      

  2.   

    Hello是什么??SpringHello实现的接口是哪个???
      

  3.   

    Hello是一个接口,SpringHello、MybatisHello是它的实现类。
    Hello:public interface Hello
    {
    public void say();
    }SpringHello:public class SpringHello implements Hello
    {
    public void say()
    {
    System.out.println("Hello Spring!");

    }
    }MybatisHello:public class MybatisHello implements Hello
    {
    public void say()
    {
    System.out.println("Hello Mybatis!");

    }
    }
      

  4.   


    Hello是一个接口,SpringHello 、MybatisHello 是它的实现类,注入接口实现类的bean给接口,感觉没错啊,不然该咋写呢?