Inject HttpServletRequest (from Struts2 action implementing ServletRequestAware) into property using Spring

ぃ、小莉子 提交于 2019-12-24 14:49:45

问题


I am using Struts2 with Spring for dependency injections.

I have Struts action A from which I can access HttpServletRequest and some dependency B inside it:

public class A extends ActionSupport implements ServletRequestAware {
    private B b;
    private HttpServletRequest request;

    @Override
    public void setServletRequest(HttpServletRequest httpServletRequest)
    {
        this.httpServletRequest = httpServletRequest;
    }

    public B getB() {
        return this.b;
    }

    public void setB(B b) {
        this.b = b;
    }
}

There is also application-context.xml:

<bean id="b" class="com.example.B" />
<bean id="a" class="com.example.actions.A">
    <property name="b" ref="b" />
</bean>

The program works, but here is my problem: dependency B requires HttpServletRequest to function properly. Is there a way for Spring to inject it in B? Right now I would need to pass HttpServletRequest object manually to methods that require it.


回答1:


Is there a way for Spring to inject it in B?

Yes, but B should be request scoped.

You pass the request object that you have got from Struts, but your actions are managed by Spring, and you want to use Spring DI to inject HttpServletRequest object? You can inject only object that is bound to thread via RequestAttributes.

You can inject this object only if it's available to Spring. You can get request object any other way but injection works only to the corresponding scope.



来源:https://stackoverflow.com/questions/36654607/inject-httpservletrequest-from-struts2-action-implementing-servletrequestaware

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