Spring 通过使用策略模式考虑特定字段,在表之间切换并保存数据
共有三个名为car_details、bike_details、truck_details的表。所有三个表的字段(RegistrationNo、No.ofYearSeld、OwnerName、ContactNo、VehicleType)都相同。字段VehicleType应指定车辆类型(汽车或自行车或卡车),其默认值为car 这三个表都有各自的POJO和存储库 任务是我需要通过考虑vehicleType字段将数据保存到相应的表中 在我的控制器中Spring 通过使用策略模式考虑特定字段,在表之间切换并保存数据,spring,spring-mvc,spring-boot,strategy-pattern,Spring,Spring Mvc,Spring Boot,Strategy Pattern,共有三个名为car_details、bike_details、truck_details的表。所有三个表的字段(RegistrationNo、No.ofYearSeld、OwnerName、ContactNo、VehicleType)都相同。字段VehicleType应指定车辆类型(汽车或自行车或卡车),其默认值为car 这三个表都有各自的POJO和存储库 任务是我需要通过考虑vehicleType字段将数据保存到相应的表中 在我的控制器中 @RequestMapping (value = "/
@RequestMapping (value = "/createVehicle/", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public ResponseEntity<> createGeneralAuthentication (@RequestBody CarDetails carDetails) {
public void roleSelector(String type) {
switch (type){
case "car":
return new CarRepository();
break;
case "bike":
return new BikeRepository();
break;
case "truk":
return new TruckRepository();
break;
}
}
RolesRepository rolesRepository = new roleSelector(carDetails.getType());
try {
rolesRepository.save(carDetails);
} catch (Exception ex) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(HttpStatus.OK);
}
@RequestMapping(value=“/createVehicle/”,method=RequestMethod.POST,consumes=“application/json”)
@应答器
公共响应性createGeneralAuthentication(@RequestBody CarDetails CarDetails){
公共无效角色选择器(字符串类型){
开关(类型){
案例“汽车”:
返回新的CarRepository();
打破
案例“自行车”:
返回新的BikeRepository();
打破
案例“truk”:
返回新的TruckRepository();
打破
}
}
RolesRepository RolesRepository=新角色选择器(carDetails.getType());
试一试{
角色存储。保存(卡片细节);
}捕获(例外情况除外){
返回新的ResponseEntity(未找到HttpStatus.NOT_);
}
返回新的响应状态(HttpStatus.OK);
}
不,如果应该使用else,则它需要是一个策略模式。实际上它已经是一个策略模式:每个实现的行为都不同,您使用单个接口来抽象它们的实现细节。这里
roleSelector
方法用于创建实例(如工厂)。我更关心的是在Spring应用程序中使用new
(很可能不起作用)。但实际上,这段代码不起作用,我所需要的是使此模式可执行它怎么不起作用?它给您带来了什么错误/异常?你为什么不在问题中提到它?我的猜测是,由于使用new
而不是注入和使用Spring中的bean,因此出现了NullPointerException。实际上,存在多个错误。我传递的对象是CardDetails,然后根据类型,我们必须选择相应的存储库。我们还需要更改对象类型以匹配存储库。我们怎么能做到呢。我试着在存储库中创建接口,但无法实现。