从java类调用控制器方法

I just want to know whether controller class method is accessible from another java class.    

以下是我的控制器及其方法.

@Controller
public class TestResultUploadController {
    @RequestMapping(method = RequestMethod.POST,value="/uploadTestResult")  
    public @ResponseBody  
     String uploadTestResult(String testResultBarcode,int deviceLoc) {

         //some code goes here
    return something;
}

我只想从另一个java类调用这个控制器方法.
    我怎样才能使它工作?
    请建议..

最佳答案
简短回答:是的,有可能.在你的其他类/线程中,你可以做到

// this will create a new instance of that controller where no fields are wired/injected
TestResultUploadController controller = new TestResultUploadController();
controller.uploadTestResult("someString", 1234); 

但是,请记住,您的设置非常不寻常,并且所有自动装配的字段都无法正确连接.如果从上下文中获取控制器,则可以正确连接/注入字段:

// obtain controller bean from context, should have fields wired properly
TestResultUploadController controller = ctx.getBean(TestResultUploadController.class);
controller.uploadTestResult("someString", 1234); 

或者你可以在你的其他课堂上:

@Autowired private TestResultUploadController controller;

....
public void doStuff(){
    controller.uploadTestResult("someString", 1234); 
}

同样,这是非常不寻常的,但很有可能.但是,只是因为有可能做某事,并不意味着你应该这样做.我建议使用更常见的Spring / MVC方法,将业务逻辑外包给Services.基本上,有这样的事情:

@Controller
public class TestResultUploadController {

    @Autowired private UploadTestResultService uploadTestResultService;

    @RequestMapping(method = RequestMethod.POST,value="/uploadTestResult")  
    public @ResponseBody String uploadTestResult(String testResultBarcode,int deviceLoc) {
        return uploadTestResultService.uploadTestResult(testResultBarcode, deviceLoc);
    }
}

在你的线程中:

//somehow get the service
UploadTestResultService uploadTestResultService = //somehowGetTheService (whether from context or in some other way)
uploadTestResultService.uploadTestResult(testResultBarcode, deviceLoc);

这样,您就可以在控制器的测试中模拟UploadTestResultService,并且您还可以自己测试该服务的uploadTestResult方法,而无需在控制器中.

编辑:
如何获取Spring上下文超出了本问题的范围.我假设你知道基本的Spring和基本的java.

转载注明原文:从java类调用控制器方法 - 代码日志