org.springframework.beans.BeanInstantiationException: не удалось создать экземпляр [org.springframework.web.servlet.HandlerMapping]: не задан ServletContext - PullRequest
0 голосов

Я пытаюсь включить SpringMVC в приложении.Приложение имеет устаревший код, и интеграция Spring довольно сложна.У меня есть основной класс под названием HttpServerRunner.В методе init этого класса я вызываю initSpringContext, который дает мне новый экземпляр контекста корневой пружины.Теперь, если я добавляю @EnableWebMvc конфигурацию, старый метод initSpringContex выбрасывает No ServletContext set.Кажется, что свойство servletContext из WebMvcConfigurationSupport является нулевым.Я упоминаю, что HttpServerRunner, основной класс, не является весенним классом.Я думаю, что я звоню new ApplicationContex т слишком рано, или что-то вроде этого.Если я удаляю конфигурацию @EnableWebMvc, я могу использовать RestControllers, но не могу вернуть объект, используя Джексона.

SpringConfiguration

- это класс, содержащий все компоненты из моего приложения:

@Configuration
@EnableScheduling
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.netoptics", "com.whitelist.manager", "com.websilicon", "com.wsnms.server", "com.anue", "com.wsnms"})
public class SpringConfiguration {

    @Bean
    ......

    @Bean
    .....

        @Bean
        ......

        @Bean
        .....

        @Bean

    }

SpringWebConfigurationэто класс для spring-mvc:

@Configuration
@EnableWebMvc
@ComponentScan({"com"})
public class SpringWebConfiguration {
}

HttpServerRunner, не относящийся к весне класс, где я пытаюсь инициировать контекст SpringConfiguration:

public class HttpServerRunner implements WsHttpServerUpdateable {
    private ApplicationContext springAppContext;

private void initSpringAppContext() {
        this.springAppContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
    }

 }

private void init(String[] args) throws Throwable { 
WsObjectRegistry.replaceInstance(RedundancyListener.class, DatabaseReplication.getInstance());
        initSpringAppContext();

        initHttpServer();
}

Итак, в методе init мне нужночтобы иметь SpringConfiguration контекст, загруженный для получения бинов.

Ошибка, которую я получил в initSpringAppContext:

Caused By: BeanCreationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)

Я могу войти в режим отладки в WebMvcConfigurationSuport, свойство servletContextявляется нулевым

web.xml

<servlet>
            <servlet-name>springMvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextClass</param-name>
                <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
            </init-param>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>com.netoptics.server.SpringWebConfiguration</param-value>
            </init-param>
        </servlet>


    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.netoptics.server.SpringConfiguration</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

<servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>/v2/*</url-pattern>
    </servlet-mapping>
...