如何在嵌入式中添加 ServletContextListener tomcat

How to add ServletContextListener in embedded tomcat

我有一个简单的嵌入式应用程序 tomcat。我正在尝试做一些初始化工作,我需要 JNDI 资源。

我想在 ServletContextListener.contextInitialized 中完成。

当我在tomcat.start()之前添加ServletContextListener时,context.getServletContext() returns null.

如果我在 tomcat.start() 之后执行此操作,则会出现错误:

Exception in thread "main" java.lang.IllegalStateException: Listeners cannot be added to context [] as the context has been initialised

这是启动器代码:

public static void main(String[] args) throws Exception {
    Tomcat server = new Tomcat();
    server.setPort(8080);

    Context context = server.addContext("", Paths.get(".").toAbsolutePath().toString());

    Tomcat.addServlet(context, "hello", new HelloServlet());
    context.addServletMappingDecoded("/", "hello");

    ContextResource resource = buildResource(
        H2_DATA_SOURCE_NAME,
        DataSource.class.getName(),
        h2DatasourceProperties()
    );

    context.getNamingResources().addResource(resource);
    context.getServletContext().addListener(DataBaseSchemaInit.class);

    server.start();
    server.getServer().await();
}

如何在嵌入式 tomcat v.8.5.28 中添加 ServletContextListener

我用 ServletContainerInitializer.

做到了
StandardContext context = buildContext(tomcat);
...
context.addServletContainerInitializer(new DataBaseInitializer(DATA_BASE_SCHEMA), null);