пружина mvc не инициализирована - PullRequest
0 голосов
/ 22 февраля 2020

Мне нужно преобразовать старое приложение Spring xml в java config no web. xml.

Я добавляю этот класс:

public class WebServletConfiguration implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) throws ServletException {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(SpringConfiguration.class);

        container.addListener(new ContextLoaderListener(rootContext));

        AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(SpringConfiguration.class);

        ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
}



@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "{com.ciro}")
public class SpringConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/static/")
                .setCachePeriod(365 * 24 * 60 * 60);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(handlerTimeLongInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/secure/**");
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/view/", ".jsp");
    }

.....



}

, но контроллер не отображается и все запросы возвращают 404. С конфигурацией xml все работает нормально. Чего мне не хватает?

1 Ответ

0 голосов
/ 22 февраля 2020

Я изменил метод таким образом, и он работает

@Override
public void onStartup(ServletContext container) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(SpringConfiguration.class);
    rootContext.scan("com.ciro");
    container.addListener(new ContextLoaderListener(rootContext));
    ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(rootContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...