如何在spring中从不同的控制器调用restcontroller方法?

deyfvvtc  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(446)

我有一个类似这样的控制器:

@RestController
@RequestMapping("/api")
public class SimulationController {

@Autowired
    private SimulationRepository simulationRepository;

@PostMapping("/simulations")
    public Simulation createSimulation(@Valid @RequestBody Simulation simulation){
        simulationRepository.save(simulation);

        return simulation;

    }
}

我想知道如何将模拟对象传递给其他控制器,这些控制器可以处理数据并将其保存到其他存储库。例如,它可以如下所示:

@PostMapping("/simulations")
    public Simulation createSimulation(@Valid @RequestBody Simulation simulation){
        simulationRepository.save(simulation);
        SimulationProcess simulationProcess = new SimulationProcess(simulation);
        simulationProcess.simulate();
        return simulation;

    }
@Controller
public class SimulationProcess {
    private Simulation simulation;

    @Autowired
    private SecondRepository secondRepository;

    public SimulationProcess(Simulation simulation) {
        this.simulation = simulation;
    }

    public void simulate(){
    // process data from this.simulation
       secondRepository.save(new Second(...));
    }
}

但我知道这种做法是不允许的。有什么办法吗?

nkoocmlb

nkoocmlb1#

我认为您可以在simulationprocess类中使用@服务而不是@控制器,您可以将其注入到第一个控制器并使用它,但是您不能将请求Map到服务(我认为)。

@RestController
@RequestMapping("/api")
public class SimulationController {

    @Autowired
    private SimulationRepository simulationRepository;

    @Autowired
    private SimulationProcess simulationProcess;

    @PostMapping("/simulations")
    public Simulation createSimulation(@Valid @RequestBody Simulation simulation){
        simulationRepository.save(simulation);

        simulationProcess.simulate(simulation);

        return simulation;

    }
}
@Service
public class SimulationProcess {

    @Autowired
    private SecondRepository secondRepository;

    public void simulate(Simulation simulation){
    // process data from this.simulation
       secondRepository.save(simulation);
    }
}

希望对你有帮助。对不起,我犯了错误,英语不是我的第一语言

相关问题