在 Spring 中将 Controller1 的方法调用到 Controller2 的另一个方法中

Call method of Controller1 into another method of Controller2 in Spring

我做了很多 Google 来找到我的问题,但我找不到,很抱歉,如果这个问题已经在堆栈上溢出,因为我没有找到它。

首先让我们看一下代码

@Controller
public class Controller1 {
    @RequestMapping(value = "URL", method = RequestMethod.GET)
    public ModelAndView methodHandler(Parameters) { 

    }

    public int calculation(int i){
        //Some Calcucation
        return i;
    }
}

第二个控制器是

@Controller
public class Controller2 {
    @RequestMapping(value = "URL", method = RequestMethod.GET)
    public ModelAndView methodHandler(Parameters) { 
        //In this I want to call the calculation(1) method of controller1.
    }
}

我的问题是有什么方法可以调用controller1的calculation()方法给controller2。但是请记住,我不想在 controller1.Is 中将方法设为静态,无论如何都可以在不将其设为静态的情况下调用它?

谢谢 亚西尔

你的控制器不应该互相调用。如果有一个逻辑需要被两个控制器使用,最好将它放入单独的 bean 中,这将被两个控制器使用。然后,您可以简单地将那个 bean 注入到需要的控制器中。尽量不要将任何业务逻辑放在控制器中,请尝试将其放在专门的 class 中,如果可能的话,它将独立于 Web,并将接受与 Web 无关的业务数据,如用户电子邮件、帐号等。没有 http 请求或响应。这样你的 class 与实际逻辑是可重用的,并且可以更容易地进行单元测试。此外,如果有状态,它应该包含在您的 classes 外部控制器中。控制器应该是无状态的,根本不包含任何状态。

当使用 MVC 模式并决定将逻辑放在哪里时,您应该将业务逻辑分离到模型和控制器中,您应该只放置与用户交互有关的逻辑,as explained in this stack overflow post

例如,您应该在配置文件中创建服务 bean(或使用 @ 注释之一)并将其注入控制器。例如 ()

@Configuration
public class MyConfig {

    @Bean
    public MyService myService(){
        return new MyService();
    }

}


@Controller
public class Controller1 {

    @Autowire
    private MyService myService;

    @RequestMapping(value = "URL", method = RequestMethod.GET)
    public ModelAndView First(Parameters) { 
        myService.calculation();
    }
}

@Controller
public class Controller2 {

    @Autowire
    private MyBean myBean;

    @RequestMapping(value = "URL", method = RequestMethod.GET)
    public ModelAndView First(Parameters) { 
        myService.calculation();
    }
}