即使以下是控制器類內部可以通過點擊某個按鈕從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 ?
}
}
我不明白。你可以詳細說明嗎? – AmitG
'StudentController sc = context.getBean(StudentController.class);' – emre
' T getBean(類 requiredType)'也可用 –