簡體   English   中英

在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中將方法設為靜態,是否有在不將其設為靜態的情況下調用它的方法?

謝謝亞西爾

您的控制器不應互相呼叫。 如果存在兩個控制器都需要使用的邏輯,則最好將其放入單獨的bean中,這將由兩個控制器使用。 然后,您可以簡單地將那個bean注入必要的控制器。 盡量不要將任何業務邏輯放到控制器上,而應盡量將其放到專門的類中,該類將盡可能地獨立於網絡,並且將接受與Web無關的業務數據作為用戶電子郵件,帳號等。 這樣,您的具有實際邏輯的類就可以重用,並且可以更輕松地進行單元測試。 同樣,如果有狀態,它應該包含在控制器外部的類中。 控制器應該是無狀態的,根本不包含任何狀態。

當使用MVC模式並決定將邏輯放置在哪里時,應將業務邏輯分為模型和控制器,您應僅將與用戶交互有關的邏輯放入, 如本堆棧溢出文章中所述

例如,您應該在配置文件中創建Service 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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM