创建一个Spring bean包含ServletRequest属性[英] Creating a Spring bean holds ServletRequest properties

本文是小编为大家收集整理的关于创建一个Spring bean包含ServletRequest属性的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我需要创建一个 Spring bean,以便它存储 HttpServletRequest 对象的 serverName、serverPort、contextPath 属性,以便我可以根据需要将此 bean 注入其他 bean.

在我看来,这些属性不会随任何 URI 改变,因此最好将其初始化一次(无论如何,多次传递 request 实例并没有那么昂贵).

问题是,如何将 HttpServletRequest 实例注入到我的配置 bean?我更喜欢基于 xml 的注入.很可能我们需要将它作为 <property> 注入,但我不知道这个 ServletRequest 对象的 name 或 ref 是什么.

目的是将这些变量保存在 bean 中,以便可以从任何 bean 访问它们,并且当我需要获取 serverName 等时,我不需要将 request 对象作为参数传递给许多方法.

任何想法如何创建这样的 bean 及其配置?

推荐答案

您可以使用 request-scoped bean,并将当前请求自动装配到您的 bean 中:

public class RequestHolder {
   private @Autowired HttpServletRequest request;

   public String getServerName() {
      return request.getServerName();
   }
}

然后在 XML 中:

<bean id="requestHolder" class="com.x.RequestHolder" scope="request">
  <aop:scoped-proxy/>
</bean>

然后,您可以将 requestHolder bean 连接到您选择的任何业务逻辑 bean.

注意 <aop:scoped-proxy/> - 这是将请求范围的 bean 注入单例的最简单方法 - 请参阅 Spring docs 了解其工作原理以及如何配置 aop 命名空间.

本文地址:https://www.itbaoku.cn/post/978612.html

问题描述

I need to create a Spring bean so that it stores serverName, serverPort, contextPath properties of a HttpServletRequest object so that I can inject this bean to other beans as I need.

In my opinion, those properties do not change with any URI so that it is good to initialize this once (anyway, passing request instance many times is not so expensive at all).

The problem is, how can I inject HttpServletRequest instance to my configuration bean? I prefer xml based injection. Most probably we need to inject it as a <property> but I do not know what will be name or ref for this ServletRequest object.

The aim is to hold those variables in a bean so that they will be accessible from any bean and I won't need to pass request object to many methods as an argument when I need to obtain serverName etc.

Any ideas how to create such a bean and its configuration?

推荐答案

You can do this using a request-scoped bean, and autowiring the current request into your bean:

public class RequestHolder {
   private @Autowired HttpServletRequest request;

   public String getServerName() {
      return request.getServerName();
   }
}

And then in the XML:

<bean id="requestHolder" class="com.x.RequestHolder" scope="request">
  <aop:scoped-proxy/>
</bean>

You can then wire the requestHolder bean into wheiever business logic bean you choose.

Note the <aop:scoped-proxy/> - this is the easiest way of injecting a request-scoped bean into a singleton - see Spring docs for how this works, and how to configure the aop namespace.