简短的回答:是的,有可能。在您的其他类/线程中,您可以执行
// 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。
简短的回答:是的,有可能。在您的其他类/线程中,您可以执行
// 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。