问题
I have :
@Controller
@RequestMapping(value="admin/*", method=RequestMethod.GET)
public class AdminController {
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;
@RequestMapping
public ResponseEntity<String> test0() {
System.out.println("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ");
return null;
}
}
and the tag:
<mvc:annotation-driven />
in my config.xml
It should be enough I feel, but there is a problem with @Autowired:
No matching bean of type [javax.servlet.http.HttpServletResponse] found for dependency: expected at least 1 bean which qualifies ...
I have seen a couple of solutions mention setting up beans and such, but I am sure there has to be some better way. The annotation-scan should take care of this. It would suck if I have to set up beans in xml for several different annotations at different times. I just want the annotations to work when I use them!
I have seen: Spring MVC - Response
Thanks!
回答1:
As a workaround try:
@RequestMapping
public ResponseEntity<String> test0(
HttpServletRequest request,
HttpServletResponse response) {
System.out.println("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ");
return null;
}
Also try adding RequestContextListener but this should't be required in Spring MVC environment.
回答2:
Autowiring doesn't work for the response, only the request. There are workarounds, but they're kind of hacky and lame. I ran into the same issue, here's my original question with a link to the workaround: @Autowired HttpServletResponse
回答3:
It does not work as you want it, as fields, because a request and respose changes after each request (in lack of better explanation). You cannot reinject every time the new request/response in the fields. That is why you have to add them in the method where they will be injected every time new.
来源:https://stackoverflow.com/questions/9719702/spring-mvc-autowired-response-not-working