找不到javax.servlet.ServletContext中的addListener方法

时间:2015-05-14 02:38:12

标签: java spring spring-mvc servlets methods

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

所以我阅读了官方文档和博客上的一些帖子。

e.g。 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实例)无法读取此方法。

感谢您的回答:D

P.S。

我的春季版本为4.1.6.RELEASE,我在servlet3.0, spring-context, spring-webmvc上加pom.xml

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

也许我遇到了一些沟通问题,所以我总结一下:D

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

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

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

而不是推荐Add cast to 'container'

2 个答案:

答案 0 :(得分:5)

为了跟进@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.

答案 1 :(得分:0)

就我而言,有:

<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时,我遇到了这个问题。

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