それ以外の場合は統合春のコンテナの見通しは+複数のデータベース管理を削除します
- 注意事項
- プロジェクトパッケージの建築存在、などの異常傍受など
- 戦略は、クラスのコメントを追加する必要が春のコンテナを統合@Compent
ビューの呼び出し
@PostMapping(value = "/strategy/normal/pay")
public BaseResource pay(@RequestParam String code) {
if(StringUtils.isEmpty(code)) {
throw new ViewParamException();
}
/**
* 从数据库获取beanId
*/
PaymentChannel paymentChannel = paymentChannelMapper.getPaymentChannel(code);
if(null == paymentChannel) {
throw new DataException();
}
String strategyBeanId = paymentChannel.getStrategyBeanId();
if(StringUtils.isEmpty(strategyBeanId)) {
throw new DataException("beanId不存在");
}
/**
* 使用spring容器通过的工具从容器中获取bean
*/
Pay pay = SpringUtils.getBean(strategyBeanId, Pay.class);
String call = pay.call();
return BaseResource.fromSuccess(call);
}
- コード
定義されたインタフェース
public interface Pay {
String call();
}
@Component
public class AliPay implements Pay {
@Override
public String call() {
System.out.println("调用支付宝");
return "ali";
}
}
@Component
public class UnionPay implements Pay {
@Override
public String call() {
System.out.println("调用银联");
return "union";
}
}
@Component
public class WxPay implements Pay {
@Override
public String call() {
System.out.println("调用微信");
return "wx";
}
}
dao 层
public interface PaymentChannelMapper {
@Select("SELECT id ,channelName ,channelId,strategyBeanId " +
"FROM payment_channel where channelId=#{payCode}")
PaymentChannel getPaymentChannel(String payCode);
}
@Data
public class PaymentChannel {
private Integer id;
/** 渠道名称 */
private String channelName;
/** 渠道ID */
private String channelId;
/**
* 策略执行beanId
*/
private String strategyBeanId;
}
YML配置
###服务启动端口号
server:
port: 8080
spring:
###数据库相关连接
datasource:
username: root
password: 17730088312@163.com
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:33061/design_pattern?useUnicode=true&characterEncoding=UTF-8&useSSL=false
テーブル構造
drop database if exists `design_pattern`;
create database `design_pattern` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE TABLE IF NOT EXISTS `payment_channel`(
`id` INT UNSIGNED AUTO_INCREMENT,
`channelName` VARCHAR(100) NOT NULL,
`channelId` VARCHAR(40) NOT NULL,
`strategyBeanId` VARCHAR(40) NOT NULL,
PRIMARY KEY ( `id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;