1

我知道如何在 Java 代码中自动装配 http 请求对象:

@Resource
private HttpServletRequest request;

我想在 xml conf 中做类似的事情。我试图实例化的 bean 将一个 http 会话对象作为构造函数参数:

    <bean class="..." scope="request">
        <constructor-arg>
             ???
        </constructor-arg>
    </bean>
4

1 回答 1

1

您可以创建一个使用此方法的工厂类:

http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/request/RequestContextHolder.html#currentRequestAttributes%28%29

例如:

<bean id="httpSessionFactory" class="HttpSessionFactory">
    <constructor-arg>true</constructor-arg>
</bean>

<bean class="..." scope="request">
    <constructor-arg>
        <bean factory-bean="httpSessionFactory"
              factory-method="getSession"/>
    </constructor-arg>
</bean>

和Java:

public class HttpSessionFactory {
    private boolean create;

    public HttpSessionFactory(boolean create) {
        this.create = create;
    }

    public static HttpSession getSession() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attr.getRequest().getSession(create);
    }
}
于 2012-11-20T23:02:05.590 回答