How do I constructor-autowire HttpServletResponse in Spring 3.1?

青春壹個敷衍的年華 提交于 2019-12-06 07:03:26

问题


I have a request scoped bean, and I need to have access to the HttpServletResponse and HttpServletRequest objects.

I need access to these objects in the constructor, so property autowiring is not an option.

I did the following:

@Component
@Scope("request")
public class MyClass{

    @Autowired(required=true)
    public MyClass(HttpServletRequest request, HttpServletResponse response) {

        // do stuff I need to do in the constructor

    }
}

This gives me the following error:

No default constructor found; nested exception is java.lang.NoSuchMethodException: com.foo.bar.MyClass.()

According to this error message, it is looking for a paramless default constructor, which does not exist. I autowired the constructor and specifically set "required" to true, so the injector should choose this constructor. Since the bean is request scope this should work, but it does not.

Any ideas?


回答1:


As far as I understand , you will not be able to autowire the HttpServletResponse object using the standard approach . Check the registerWebApplicationScopes method of the WebApplicationContextUtils class . The resolvable dependencies are only the HttpSession.class and HttpSession.class .

Check for a cusom solution here .




回答2:


As @Aravind mentioned, HttpServletResponse is not available as an autowire candidate. However, you can get access to the response using ServletWebRequest.getResponse(), and ServletWebRequest (a Spring-specific class) is available as an autowire candidate.

Having said that, it may not work in the constructor, but give it a go anyway :)



来源:https://stackoverflow.com/questions/8887831/how-do-i-constructor-autowire-httpservletresponse-in-spring-3-1

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