0

我有一个包含许多 servlet 的大型 Java 项目。并且每个 servlet 需要使用以下命令从同一个 bean 文件中获取对象:

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

然后我用

     context.getBean("<BEAN_NAME">);

其中一些甚至需要获得相同的对象。

问题是是否可以将我想要的对象直接注入 servlet 而无需手动读取 bean 文件。

每个 servlet 都在 web.xml 中配置。

任何有关该问题的信息将不胜感激!

谢谢

4

3 回答 3

2

您是否考虑过让您的 servlet 实现HttpRequestHandler

然后,您必须将您的 Servlet 声明为名为 Spring bean 并在 web.xml 上使用相同的名称,然后您可以简单地使用 @Autowired 注释将 Spring bean 注入您的 Servlet

更多信息请访问http://www.codeproject.com/Tips/251636/How-to-inject-Spring-beans-into-Servlets

示例代码:


  @Component("myServlet") 
   public class MyServlet implements HttpRequestHandler {

        @Autowired
        private MyService myService;
...

示例 web.xml

<servlet>     
            <display-name>MyServlet</display-name>
            <servlet-name>myServlet</servlet-name>
            <servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet
           </servlet-class>
    </servlet>
    <servlet-mapping>
            <servlet-name>myServlet</servlet-name>
            <url-pattern>/myurl</url-pattern>
    </servlet-mapping>
于 2013-07-10T14:00:41.123 回答
1

您可以使用 a SerlvetContextListenerwithServlet#init()方法。当你的 servlet 容器创建一个 servlet 上下文时,它将调用contextInitialized()任何ServletContextListener你可以对应用程序单例/beans/等进行初始化的 s。

public class YourServletContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // clear context
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        // initialize spring context    
        event.getServletContext().setAttribute("context", springContext);
    }
}

此上下文(servlet 上下文)中的所有 Servlet 都可以访问这些属性。

在 Servletinit()方法中,您只需获取属性

public class YourServlet implements Servlet {

    @Override
    public void init(ServletConfig config) {
        config.getServletContext().getAttribute("context");
        // cast it (the method returns Object) and use it
    }

    // more
}
于 2013-07-10T13:51:30.240 回答
1

由于您有一个 Web 应用程序,我会使用WebApplicationContextcontains in spring-web,它在您的 Web 应用程序的部署时加载并在取消部署时正确关闭。您所要做的就是ContextLoaderListener在您的web.xml:

<listener>
   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

然后您可以ApplicationContext从任何 servlet 访问您的:

ApplicationContext ctx = WebApplicationContextUtils
    .getRequiredWebApplicationContext(getServletContext());
MyBean myBean = (MyBean) ctx.getBean("myBean");
myBean.doSomething();

优点是,您的上下文在所有 servlet 之间共享。

参考:

于 2013-07-10T13:51:37.623 回答