2017-02-15 54 views
1

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); 

    } 
} 

即使我在CallingApp类给予预选赛@Qualifier("BasicPhone"),我得到异常如下:

没有符合条件的bean类型[com.geekslab.device的。电话]定义:预期单个匹配的bean,但发现2:BasicPhone,智能手机

+0

你可以删除'@ComponentScan(basePackages = { “com.codegeekslab.type”})'从服务类,然后尝试? – SachinSarawgi

+0

@SachinSarawgi得到了答案,thnaks反正 – sdvadsa

回答

5

您通过电话在你CallingApp构造函数参数服务而不指定bean。

尝试在您的构造函数中添加限定符,或者坚持自动注入,这是您已经做的事情。

+1

你是对的thankx – sdvadsa

0

我删除了CallingApp类的构造函数,它工作。

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

As Constructor重写了setter方法。

0

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

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