2013-10-01 58 views
0

運行控制器中的方法我有一個控制器類:如何從外部控制器

@Controller 
public class MyController { 

@AutoWired 
Service myservice 

@RenderMapping 
public display(){ 
    //do work with myservice 
} 

} 

我要調用從外部類中的方法顯示(),但我是一個空指針異常。

這裏是我如何從外部調用類的顯示方法:

new MyController.display() 

但實例爲MyService被設置爲null。

如何調用MyController.display()並確保myservice的實例未設置爲null?

我認爲問題是因爲我正在創建控制器的新實例,該服務然後不自動裝配?但是因爲Spring控制器是單例的,也許我可以訪問控制器的當前實例嗎?

更新:

的原因,我想這是我加入一個配置選項來確定哪個控制器顯示方法應該實現。也許我應該使用超級控制器來確定應該實現哪個控制器?

+0

你需要使用Spring上下文來獲取這樣myController的所有的依賴注入。如果您使用new創建實例,則彈簧的全部點將被取消。還要檢查myservice的setters和getters是否已經到位 –

+0

你不能手動創建這個類的實例,它是由spring管理的,有一種骯髒的方式來實現這一點,但不建議這樣做。充其量你告訴我們,你的用例是什麼,那麼我們可能會幫助找出一個解決方案 – Jaiwo99

+0

@ Jaiwo99請參閱更新 –

回答

1

這個想法是:使用抽象的父類!

// this class has no mapping 
public abstract class MyAbstractController() { 
    @Autowired 
    MyService service 

    public String _display(Model model, ...) { 
    // here is the implementation of display with all necessary parameters 
    if(determine(..)){...} 
    else {...} 
    } 

    // this determines the behavior of sub class 
    public abstract boolean determin(...); 
} 

@Controller 
@RequestMapping(...) 
public class MyController1 extends MyAbstractController { 

    @RequestMapping("context/mapping1") 
    public String display(Model model, ...) { 
    // you just pass all necessary parameters to super class, it will process them and give you the view back. 
    return super._display(model, ...); 
    } 

    @Override 
    public boolean determine(...) { 
    // your logic for this 
    } 
} 

@Controller 
@RequestMapping(...) 
public class MyController2 extends MyAbstractController { 

    @RequestMapping("context/mapping2") 
    public String display(Model model, ...) { 
    // you just pass all necessary parameters to super class, it will process them and give you the view back. 
    return super._display(model, ...); 
    } 

    @Override 
    public boolean determine(...) { 
    // your logic for this 
    } 
} 

希望這可以幫助你......

0

我認爲這個問題是因爲我創建了一個 控制器的新實例,該服務然後不自動佈線?

是。您可以在Spring中使用BeanFactory API訪問您的bean。但直接調用控制器聽起來很腥。你能告訴我們你想達到什麼目的嗎?可能我們可以看看是否有標準的做法?

+0

請看更新 –

+0

你可以做請求轉發嗎?如果是,您可以根據配置選項將DispatcherServlet轉發到其他控制器。像這樣的東西:http://stackoverflow.com/a/7366199/2231632 – prabugp

相關問題