WebApplicationInitializer を使用して、no-web.xml 構成のコードをいくつか検索しました。
これらのコードは同じ形式です。
- rootContext を作成する
- ContextLoaderListener を作成する
- Listener をサーブレットに登録する
ここにコードブロックがあります
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
registerListener(servletContext);
registerDispatcherServlet(servletContext);
}
private void registerListener(ServletContext servletContext) {
AnnotationConfigWebApplicationContext rootContext = createContext(DomainConfiguration.class);
ContextLoaderListener contextLoaderListener = new ContextLoaderListener(rootContext);
servletContext.addListener(contextLoaderListener);
servletContext.addListener(new RequestContextListener());
}
private void registerDispatcherServlet(ServletContext servletContext) {
AnnotationConfigWebApplicationContext dispatcherContext = createContext(WebMvcContexConfiguration.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME,
new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
private AnnotationConfigWebApplicationContext createContext(final Class<?>... annotatedClasses) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(annotatedClasses);
return context;
}
しかし、このコードは機能していません。ルート コンテキストでコンテキスト化されたオブジェクトが見つかりません。それで、私はいくつかのコードを変更しました、それは働いています。
これが作業コードです。
private void registerListener(ServletContext servletContext) {
AnnotationConfigWebApplicationContext rootContext = createContext(DomainConfiguration.class);
ContextLoaderListener contextLoaderListener = new ContextLoaderListener(rootContext);
// This is changed code!!
contextLoaderListener.initWebApplicationContext(servletContext);
servletContext.addListener(new RequestContextListener());
}
そうですか?春のヘルプドキュメントに最初のコードが表示されます。しかし、桟橋9では機能しません。