本文介绍了创建Spring bean包含ServletRequest属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



在我看来,这些属性不会更改任何URI,以便初始化一次(无论如何,多次传递请求实例并不是那么昂贵)。



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



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



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

解决方案

您可以使用,并将当前请求自动装入你的bean:

  public class RequestHolder {
private @Autowired HttpServletRequest request;

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

然后在XML中:

 < bean id =requestHolderclass =com.x.RequestHolderscope =request> 
< aop:scoped-proxy />
< / bean>

然后您可以将 requestHolder bean连接到你选择的业务逻辑bean。



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

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.

这篇关于创建Spring bean包含ServletRequest属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 21:40