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这个实现类。

 

posted @ 2021-01-15 18:25  JamesPlay  阅读(4467)  评论(0编辑  收藏  举报