gpt4 book ai didi

java - 使 ServletContextListener 具有 Spring 意识

转载 作者:IT老高 更新时间:2023-10-28 13:51:35 27 4
gpt4 key购买 nike

我正在将 Spring 插入现有的 Java EE Web 应用程序。我的 web.xml 中有以下几行:

<listener>
<listener-class>com.MyContextListener</listener-class>
</listener>

然后跟随 MyContextListener 类?

public class MyContextListener implements ServletContextListener {

public void contextInitialized(ServletContextEvent event) {
//...
}
}

我应该怎么做才能让MyContextListener被Spring管理?


已编辑:

我的假设是:Spring 应该创建所有 servlet 和所有 Web 应用程序基础架构,因此 MyContextListenercontextInitialized 方法中发生的一切都应该由 Spring 以某种方式处理。我怎么能通过实现我想的一些接口(interface)来实现。如果我错了,请纠正我。谢谢!

最佳答案

嗯,

我们有一个类似的场景,将现有的 Jersey Web 服务应用配置为使用 Spring 进行依赖注入(inject)。我们的 Jersey webapp 扩展了 ContextLoaderListener 如下

public class XServletContextListener extends ContextLoaderListener {
...
@Override
public void contextInitialized(ServletContextEvent arg0) {
super.contextInitialized(arg0);
....
}

@Override
public void contextDestroyed(ServletContextEvent arg0) {
super.contextDestroyed(arg0);
....
}
}

其中 ContextLoaderListener

import org.springframework.web.context.ContextLoaderListener;

我们包含了 jersey-spring 桥和所有 spring 依赖项,包括 applicationContext.xml 如下

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<context:component-scan base-package="com.xxx.*" />
....
....
</beans>

显然需要确保 XServletContextListener 包含在 web.xml 中,如下所示

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>com.xxx.**.XServletContextListener</listener-class>
</listener>

之后是 servlet 及其 init-param 值和 servlet 映射。您显然可以采用注释配置代替 xml confib,在这种情况下,您需要使用 WebListener 注释。

我们使用各种注解如

@Component for objects
@Service for services
@Repository for DAOs
@Controller for controllers/resources
@ContextConfiguration for tests

一切都由 Spring 框架加载和 Autowiring

关于java - 使 ServletContextListener 具有 Spring 意识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39917592/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com