BankFileStrategy
java">public interface BankFileStrategy {String getBankFile(String bankType) throws Exception;
}
java">@Slf4j
@Component
public class ConcreteStrategy implements BankFileStrategy {@Overridepublic String getBankFile(String bankType) throws Exception {....业务代码}
java">public enum BankTypeClassEnum {//strategyA("ICBC", "concreteStrategy"),;private String name;private String implName;public static String getImplName(String name) {if (StringUtils.isBlank(name)) {return null;}for (BankTypeClassEnum aEnum : BankTypeClassEnum.values()) {if (aEnum.getName().equals(name)) {return aEnum.getImplName();}}return null;}BankTypeClassEnum(String name, String implName) {this.name = name;this.implName = implName;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getImplName() {return implName;}public void setImplName(String implName) {this.implName = implName;}
}
java">@Slf4j
@Component
public class BankFileContext {//当一个接口有多个实现类时,Spring会自动将Strategy接口的实现类注入到这个Map中,key为bean id,value值则为对应的策略实现类@Autowiredprivate Map<String, BankFileStrategy> bankFileStrategyMap;/*** 执行类*/public String execute(String bankType) throws Exception {BankFileStrategy service = bankFileStrategyMap.get(BankTypeClassEnum.getImplName(bankType));return service.getBankFile(bankType);}
}
java">@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestBankFileController {private final BankFileContext bankFileContext;@GetMapping(value = "/bank/{bankType}/file")public String testBankFile(@PathVariable String bankType) {try {return bankFileContext.execute(bankType);} catch (Exception e) {log.error("testBankFile is error", e);return "error";}}
}