简体   繁体   English

如何在仅使用批注实现相同接口的不同类中使用@autowired

[英]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" 例如,我需要将我的班级命名为“ Test_2”

Interface: 接口:

public interface Inter {

 public void useInterface();

}

Class 1: 第1类:

public class Test_1 implements Inter {

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

Class 2: 第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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何实例化(在方法内部)实现同一接口的不同类? - How to instantiate (inside a method) different classes that implement the same interface? 如何使用 Spring 配置文件模拟实现相同接口的不同服务 - How to use Spring profiles to mock different services that implement the same interface 在Java中,如何区分实现相同接口的类? - In Java, how to distinguish classes that implement the same interface? 如何注入实现同一接口的两个不同类的两个实例? - How to inject two instances of two different classes which implement the same interface? spring @autowired如何为接口和实现类工作 - How spring @autowired works for interface and implementation classes 如何给两个不同的类相同的接口? - How to give two different classes the same interface? 如何为不同类别的不同数据类型实现接口 - How to implement an interface for different classes of different data types 如何分离实现相同接口的两个类的函数模拟? - How to separate function mocks of two classes that implement the same interface? 如何为实现相同接口的两个类制作双向适配器? - How to make bidirectional adapter for two classes that implement the same interface? 泛型 - 如何定义只采用实现特定接口的类的方法 - Generics - how to define a method that takes only classes that implement a particular interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM