问题
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