[英]Get servletcontext for factory class in spring
I want to create Factory Class. 我想创建工厂类。 for example is FooFactory.
例如FooFactory。 before Foo instanced, FooFacoty must be injected ServletContext to the constructor.
在Foo实例化之前,必须将FooFacoty注入ServletContext到构造函数。 I have snippet as follows:
我有如下片段:
public class FooFactory() {
public static Foo getFoo() {
ctx = //getservlet context
Foo foo = new Foo(ctx);
return foo;
}
}
I came across this post on my search for how to do this very thing. 我在寻找如何执行此操作的过程中遇到了该帖子。 It helped me as a starting point, but since
ServletContextFactoryBean
is deprecated in Spring 3, I had to try something different. 它以帮助我为起点,但是由于
ServletContextFactoryBean
在Spring 3中已弃用,因此我不得不尝试一些不同的方法。
I found two options: 我发现了两个选择:
@Autowired
public AnAutowiredConstructor(WebApplicationContext webApplicationContext)
{
servletContext = webApplicationContext.getServletContext();
}
Or you can implement org.springframework.web.context.ServletContextAware
. 或者,您可以实现
org.springframework.web.context.ServletContextAware
。
public class SomeClass implements ServletContextAware
{
public void setServletContext(ServletContext servletContext)
{
}
}
EDIT: You can use ServletContextFactoryBean
. 编辑:您可以使用
ServletContextFactoryBean
。 You can then pass a reference to this into your factory (eg as a method argument.). 然后,您可以将对此的引用传递到工厂中(例如,作为方法参数。)。 Like this
像这样
<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>
You then change FooFactory.getFoo
to 然后,将
FooFactory.getFoo
更改为
public static Foo getFoo(ServletContext ctx) {
Foo foo = new Foo(ctx);
return foo;
}
There is no direct way that I know of, but you can do it indirectly by implementing ServletContextAware or ApplicationContextAware.
我没有直接了解的方法,但是可以通过实现ServletContextAware或ApplicationContextAware间接实现。
This article describes the details.
本文介绍了详细信息。
You can directly inject the instance of ServletContext which is kept by the Spring WebApplicationContext into you bean using xml: 您可以使用xml将Spring WebApplicationContext保留的ServletContext实例直接注入到bean中:
<bean id="myBean" class="foo.bar.SomeClass">
<constructor-arg ref="servletContext"/>
Indeed the servlet context is registered in the application context as "servletContext". 实际上,servlet上下文在应用程序上下文中注册为“ servletContext”。 See http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/web/context/WebApplicationContext.html#SERVLET_CONTEXT_BEAN_NAME .
参见http://docs.spring.io/spring/docs/4.0.x/javadoc-api/org/springframework/web/context/WebApplicationContext.html#SERVLET_CONTEXT_BEAN_NAME 。 Also works with Spring 3.x
也适用于Spring 3.x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.