简体   繁体   中英

How to use @autowired in different classes that implement the same interface with only annotations

As I can choose which class to call only with annotations? For example i need to call my class "Test_2"

Interface:

public interface Inter {

 public void useInterface();

}

Class 1:

public class Test_1 implements Inter {

 public void useInterface(){
   System.out.println("Instance Class Test_1");
 }  
}

Class 2:

public class Test_2 implements Inter {

 public void useInterface(){
   System.out.println("Instance Class Test_2");
 }  
}

Class Call:

public class Call {

 @Autowired
 private Inter inter;

 public Call(){
   inter.useInterface();
 }

}

anotate your classes this way:

@Component("test1")
public class Test_1 implements Inter {

    public void useInterface(){
        System.out.println("Instance Class Test_1");
    }  
}

and use

@Autowired
@Qualifier("test1")
private Inter inter;

You need to use qualifier, ie:

@Autowired
@Qualifier("test_2")
private Inter inter;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM