代码之家  ›  专栏  ›  技术社区  ›  ahmet alp balkan

创建一个springbean包含ServletRequest属性

  •  0
  • ahmet alp balkan  · 技术社区  · 14 年前

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

    request

    HttpServletRequest 实例到我的配置bean?我更喜欢基于xml的注入。很可能我们需要注射它作为 <property> name ref ServletRequest 对象。

    其目的是将这些变量保存在bean中,这样就可以从任何bean访问它们,而无需传递 当我需要获得 服务器名 等。

    1 回复  |  直到 14 年前
        1
  •  4
  •   skaffman    14 年前

    你可以使用 request-scoped 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。

    注意 <aop:scoped-proxy/> -这是将请求范围的bean注入单例的最简单方法—请参阅 Spring docs aop 命名空间。