无法从 javax.servlet.ServletContext 中找到 addListener 方法

can not find addListener method from javax.servlet.ServletContext

我正在尝试将 spring xml 设置更改为基于纯代码的设置。

所以看了官方文档和博客的一些帖子。

例如http://docs.spring.io/spring-framework/docs/4.1.x/javadoc-api/org/springframework/web/WebApplicationInitializer.html

我做了一个代码...

public class TestInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container)
            throws ServletException {
        // TODO Auto-generated method stub
        System.out.println("on Startup method has called.");
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(RootConfig.class);
        container.


        //container.addListener(new ContextLoaderListener(ctx));
    }
};

这里有问题。在那些页面中,他们使用 addListener(new ContextLoaderListener(ctx)) 方法来设置上下文。但是我的日食无法从 container 变量中找到该方法。

我不知道为什么我的容器变量(javax.servlet.ServletContext 实例)无法读取此方法。

感谢您的answer:D

P.S.

我的 spring 版本是 4.1.6.RELEASE,我在 pom.xml 上包含 servlet3.0, spring-context, spring-webmvc

========================

可能是我沟通有问题,所以我总结一下:D

=================================

编辑。这不是控制台上的错误。然而,这是我收到的唯一信息。 它来自 eclipse 工具包。

The method addListener(ContextLoaderListener) is undefined for the type ServletContext

比推荐值 Add cast to 'container'

跟进@JuneyoungOh 的评论,原来问题是因为依赖冲突。这些是解决这个问题的方法:

* make version 3.0.1 and artifactId 'javax.servlet-api' or
* add tomcat(in my case 7.0) to project build path and remove servlet dependency.

在我的例子中,问题是因为 Spring-Support 依赖于 "javax.servlet",我只是排除了它:

     <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-support</artifactId>
        <version>${spring-support.version}</version>
        <exclusions>
            <exclusion>
                <artifactId>servlet-api</artifactId>
                <groupId>javax.servlet</groupId>
            </exclusion>
        </exclusions>
    </dependency>

在我的例子中有:

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>

注意,artifactId 是 servlet-api,而不是 javax.servlet-api.

我已经创建了一个遗留 MVC 项目,这就是我拥有这个包的原因。当我尝试将 .xml 配置转换为 Java 时,我遇到了这个问题。

当然它与问题中的不一样,但它显示为 google 搜索中的第一个结果。