SpringBoot 中同一個接口有多個實現類的配置


1.先定義一個服務接口類:

public interface InterfaceService {
 
    String start(String key);
}

2.定義第一個實現類:

@Configuration
@ConditionalOnProperty(name="action.type",havingValue = "ALIYUN")
public class AliyunServiceImpl implements InterfaceService {
    public String start(String key) {
        return key;
    }
}

3.定義第二個實現類:

@Configuration
@ConditionalOnProperty(name="action.type",havingValue = "AWS")
public class AwsServiceImpl implements InterfaceService {
    public String start(String key) {
        return key;
    }
}

4.定義Property, 可以在yaml文件,或者property文件中

action.type: AWS

說明:

同時添加下面兩個注解:

@Configuration
@ConditionalOnProperty

Configuration 有 service的功能,不需要單獨添加Service注解,系統會根據yaml文件中配置的屬性值確定使用哪個實現類。上面的示例會跑AwsServiceImpl這個實現類。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM