如何从 Spring 中的不同控制器调用 RestController 方法?

How to call in RestController method from different Controller in Spring?

我有如下所示的 RestController:

@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(...));
    }
}

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

我认为您可以在 SimulationProcess class 中使用 @Service 而不是 @Controller,您可以注入它到你的第一个控制器并使用它,但你不能将请求映射到服务(我认为)。

@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);
    }
}

希望对您有所帮助。对于任何错误,我深表歉意,英语不是我的母语 :D