2014-03-04 21 views
0

即使以下是控制器類內部可以通過點擊某個按鈕從web瀏覽器調用,但一些我如何從main方法調用StudentController類中的doSomething方法。我在某些時候不會使用瀏覽器,但仍然需要從main方法調用控制器類方法。 由於當前的代碼複雜性,我將無法移動Utility類中的doSomething()方法。
所以我需要一個通過創建StudentController類的對象來調用doSomething()方法的解決方案。如何在主要方法中創建spring控制器類對象?

import org.springframework.context.annotation.AnnotationConfigApplicationContext; 
import org.springframework.context.ApplicationContext; 
@Controller 
@RequestMapping("/studentController") 
public class StudentController { 

    @Autowired 
    private Subject subject; 

    public String doSomething() 
    { 
     return "something"; 
    } 
} 

class Test 
{ 
    //some how I have to invoke doSomething method which is inside StudentController class. 
    // I won't be able to move doSomething() method in Utility class due to current code complexity 
    // So I need a solution to invoke doSomething() method by creating StudentController class's object. 
    // Please check whether following is a correct code. 

    public static void main(String args[]) 
    { 
     //what to do here ? This is spring MVC. 
     ApplicationContext context = new AnnotationConfigApplicationContext(StudentController.class);// is this right way? 
     StudentController sc = (StudentController)context.getBean("studentController");//what about subject injection 
     sc.doSomething(); //is this correct coding ? 

    } 

} 

回答

0

ApplicationContext#getBean - 返回bean實例中BeanFactory接口,它從簧片上下文返回bean實例可用

getBean方法。

例如 -

StudentController obj = (StudentController) context.getBean("studentcontroller"); 

依賴將被注入爲你配置,conext會自動解決依賴,並注入到bean類。

+0

我不明白。你可以詳細說明嗎? – AmitG

+1

'StudentController sc = context.getBean(StudentController.class);' – emre

+1

' T getBean(類 requiredType)'也可用 –

0

你可以通過手動加載應用程序上下文來做你想做的事情,並從中獲取「StudentController」bean。 例如:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("<path-to-your-application-context-xml-file>"); //if your application configuration is Java based, you should use another context class 
//or 
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(<you-configuration-Java-class>); 
StudentController controller = (StudentController)applicationContext.getBean("studentController"); 
controller.doSomething(); 

Full example。 希望這有助於。

+0

我正在使用註釋控制器文件。我沒有.xml文件。 – AmitG

相關問題