Spring MVC @AutoWired response not working

不打扰是莪最后的温柔 提交于 2019-12-12 15:53:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!