问题
I have two methods in my controller:
- a public method
- a private method
They all have @requestMapping and they all quotes a global variable(@autowrite). The problem is that the first method the variable has value and the second method variable is null.
Please help me.
/**
* Both of these methods are accessible through the browser,
* when i ask for query1 the flowService has value but
* when i ask for query2 the flowService is null.
* My spring version is 4.2.4
* Created by hanxiaofei on 2017/10/12.
*/
public class TestController {
@Autowired
private FlowService flowService;
@RequestMapping(value = {"/query1"})
@ResponseBody
public CommonListResult<WorkOrderMO> query1() {
return flowService.queryWorkOrderList(1);
}
@RequestMapping(value = {"/query2"})
@ResponseBody
private CommonListResult<WorkOrderMO> query2() {
return flowService.queryWorkOrderList(1);
}
}
回答1:
Controller methods annotated with @RequestMappings must be public in order to work correctly. There is no reason to make request methods as private anyway as you are not supposed to call controller methods by yourself from different components anyway.
回答2:
Again If you don't want to call it then what is the advantage in declaring it, You can't call it from any other class due to private nature and also controller methods not meant to be called from other classes and you don't want to call it from the browser because you will not be able to.
So how are you testing that flowService is null in query2 method because you will not be calling it from anywhere?
However, your problem has nothing to deal with this private and public controller method, it is something else because flowService is an instance variable and if query1 method is able to able to access it then query2 should do it as well.
回答3:
Spring MVC controllers works with any scope: public, private, protected or package-private access modifier.
You can validate it with this sample controller that works fine:
@RestController
public class TestController {
@Autowired
private FlowService flowService;
@RequestMapping("/query1")
public List<String> query1() {
return flowService.queryWorkOrderList(1);
}
@RequestMapping("/query2")
private List<String> query2() {
return flowService.queryWorkOrderList(2);
}
@RequestMapping("/query3")
protected List<String> query3() {
return flowService.queryWorkOrderList(3);
}
@RequestMapping("/query4")
List<String> query4() {
return flowService.queryWorkOrderList(4);
}
}
I have tested it with Spring Framework 4.3.11.RELEASE so the first thing to try for your issue it to use the latest version available.
That's said, I don't see why somebody would like to use private controller methods. public is most frequently used but specifying no scope is shorter and produce the same result (query4() in my example).
来源:https://stackoverflow.com/questions/46684838/private-method-with-springmvc