预选赛不在春季工作

时间:2017-02-15 09:37:57

标签: java spring autowired qualifiers

CallingApp.java

@Service
@ComponentScan(basePackages = { "com.codegeekslab.type" })
public class CallingApp {

    @Autowired
    @Qualifier("BasicPhone")
    private Phone phone;

    public CallingApp(Phone phone) {
        this.phone = phone;
    }

    public void makeCall(int number) {
        phone.openApp(number);
    }

}

Phone.java

package com.geekslab.device;

public interface Phone {

    public void openApp(int number);

}

BasicPhone.java

package com.codegeekslab.type;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.geekslab.device.Phone;
@Component("BasicPhone")
 public class BasicPhone implements Phone {
    {
        System.out.println("BasicPhone");
    }

    public void openApp(int number) {
        System.out.println("calling via simcard... " + number);
    }

}

SmartPhone.java

package com.codegeekslab.type;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.geekslab.device.Phone;

@Component("SmartPhone")
public class SmartPhone implements Phone {
    {
        System.out.println("SmartPhone");
    }

    public void openApp(int number) {
        System.out.println("calling via whatsapp..." + number);
    }

}

Test.java

package com.codegeekslab.test;

 import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.codegeekslab.app.CallingApp;
import com.codegeekslab.type.BasicPhone;
import com.codegeekslab.type.SmartPhone;
import com.geekslab.device.Phone;

 public class Test {

    public static void main(String[] args) {

        //ApplicationContext context =
        //      new GenericXmlApplicationContext("beans.xml");
        //SpringHelloWorld helloSpring  = context.getBean("springHelloWorld", SpringHelloWorld.class);
        //comment this for xml less spring 
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
         context.scan("com.codegeekslab.app","com.codegeekslab.type");
        //context.register( BasicPhone.class,SmartPhone.class,CallingApp.class);
         context.refresh();
        CallingApp  callingApp  = context.getBean("callingApp", CallingApp.class);  
        callingApp.makeCall(99999);

    }
}

即使我在@Qualifier("BasicPhone")课程中将限定符作为CallingApp,我也会得到例外,如下所示:

  

没有定义[com.geekslab.device.Phone]类型的限定bean:期望的单个匹配bean但找到2:BasicPhone,SmartPhone

3 个答案:

答案 0 :(得分:5)

您在CallingApp服务中将phone作为构造函数参数传递,而不指定bean。

尝试在构造函数中放置一个限定符,或者坚持使用autowire注入,这是你已经做过的事情。

答案 1 :(得分:0)

我删除了CallingApp类构造函数,但它工作正常。

 public CallingApp(Phone phone) {
                this.phone = phone;
            }

As Constructor重写了setter方法。

答案 2 :(得分:0)

您需要添加无参数构造函数

public CallingApp(){
    //do nothing
}
public CallingApp(Phone phone) {
    this.phone = phone;
}