如何在main方法中创建spring控制器类对象?

时间:2014-03-04 09:00:22

标签: java spring spring-mvc

即使以下是控制器类内部,可以通过点击某个按钮从Web浏览器调用,但是我必须从main方法调用StudentController类中的doSomething方法。我在某些时候不会使用浏览器,但仍然需要从main方法调用控制器类方法。 由于当前的代码复杂性,我无法在Utility类中移动doSomething()方法 所以我需要一个解决方案来通过创建StudentController类的对象来调用doSomething()方法。

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 ? 

    }

}

2 个答案:

答案 0 :(得分:0)

ApplicationContext#getBean - 返回bean实例

getBean接口中提供的

BeanFactory方法,它从spring上下文返回bean实例。

例如 -

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

依赖关系将在您配置时注入,conext将自动解析依赖关系并注入bean类。

答案 1 :(得分: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。 希望这会有所帮助。