【问题标题】:Get servletcontext for factory class in spring在spring中获取工厂类的servletcontext
【发布时间】:2010-06-24 23:42:29
【问题描述】:

我想创建工厂类。例如是 FooFactory。在 Foo 实例化之前,必须将 FooFacoty 注入 ServletContext 到构造函数。我的sn-p如下:

public class FooFactory() {
    public static Foo getFoo() {
        ctx = //getservlet context
        Foo foo = new Foo(ctx);

            return foo;
    }
}

【问题讨论】:

    标签: java spring servlets


    【解决方案1】:

    编辑:您可以使用ServletContextFactoryBean。然后,您可以将对此的引用传递给您的工厂(例如,作为方法参数。)。像这样

       <bean id="servletContext" class="org.springframework.web.context.support.ServletContextFactoryBean"/>
    
       <bean id="foo" class="FooFactory" factory-method="getFoo">
          <constructor-arg index="0" ref="servletContext"/>
       </bean>
    

    然后您将FooFactory.getFoo 更改为

       public static Foo getFoo(ServletContext ctx) {
            Foo foo = new Foo(ctx);
            return foo;
       }
    

    据我所知,没有直接的方法,但您可以通过实现 ServletContextAware 或 ApplicationContextAware 来间接实现。

    This article 描述了细节。

    【讨论】:

    • 注意:ServletContextFactoryBean 在 Spring 3 中已弃用
    • 哦,这有点可惜?有其他选择吗?
    【解决方案2】:

    我在搜索如何做这件事时遇到了这篇文章。它作为一个起点帮助了我,但由于 ServletContextFactoryBean 在 Spring 3 中被弃用,我不得不尝试一些不同的东西。

    我找到了两个选择:

    @Autowired
    public AnAutowiredConstructor(WebApplicationContext webApplicationContext)
    {
        servletContext = webApplicationContext.getServletContext();
    }
    

    或者你可以实现org.springframework.web.context.ServletContextAware。

    public class SomeClass implements ServletContextAware
    {
        public void setServletContext(ServletContext servletContext)
        {
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用 xml 将 Spring WebApplicationContext 保存的 ServletContext 实例直接注入到您的 bean 中:

      <bean id="myBean" class="foo.bar.SomeClass">
          <constructor-arg ref="servletContext"/>
      

      事实上,servlet 上下文在应用程序上下文中注册为“servletContext”。见http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/web/context/WebApplicationContext.html#SERVLET_CONTEXT_BEAN_NAME。也适用于 Spring 3.x

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多