没有设置ServletContext尝试通过码头网络服务器启用Spring MVC

时间:2019-05-10 14:40:38

标签: java spring spring-mvc servlets jetty

我正在尝试在具有码头Web服务器的现有应用程序中启用Spring-MVC。我有两个与@Configuration一起使用的类,一个与应用程序中的所有bean一起使用,一类是我使用@EnableWebMvc启用了mvc的。然后,在启动码头服务器之前,我将处理程序添加为DispatcherServlet。问题是在设置spring上下文后,我需要从中获取一个bean,但是当我在context上调用refresh时,我会收到:

 Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set

我试图初始化上下文以在非spring类中获取bean,因为它是一个遗留类:

private void initSpringAppContext() {
        this.springAppContext = new AnnotationConfigWebApplicationContext();
        ((AnnotationConfigWebApplicationContext) this.springAppContext).register(SpringConfiguration.class);
        ((AnnotationConfigWebApplicationContext) this.springAppContext).refresh();
    }

SpringWebConfiguration:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.whitelist.manager.resources")
public class SpringWebConfiguration implements WebMvcConfigurer {


}

SpringConfiguration:

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

    @Bean
        .....
        @Bean
        .....

}

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>

问题在此行上:springAppContext.refresh(); 如果我删除此邮件,并尝试致电springAppContex.getBean(),则会收到:

 java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext

更新:尝试使用XML更改Java配置,相同错误。当我尝试获取spring上下文(SpringConfiguration.class)时。因此,我无法获得用于访问bean的根上下文。 initSpringAppContext()

中我在做什么错

0 个答案:

没有答案