如何在旧web.xml中使用@Configuration引导spring应用程序?假设我正在构建一个使用@Configuration @ComponentScan注释风格的spring项目,那么如何让它与web.xml一起工作呢?在哪里启动config类?我确实尝试了下面的代码,但它似乎不起作用。
src/main/java/com/example/springconfig/AppConfig.java
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <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.example.springconfig.AppConfig
        </param-value>
    </context-param>
</web-app>src/main/webapp/WEB-INF/web.xml
package com.example.springconfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
@ComponentScan("com.example")
public class AppConfig {
    public static void main(String[] args) {
        System.out.println("===========================");
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
    }
}主要的方法从来没有被调用过,知道吗?
发布于 2022-01-17 15:14:21
基本上,您需要将ContextLoaderListener添加到web.xml,将contextClass配置为AnnotationConfigWebApplicationContext,并将contextConfigLocation配置为@Configuration的类:
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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.example.config.Config1,
        com.example.config.Config2
    </param-value>
</context-param>如果您有许多配置,而不是在web.xml中声明所有配置,您可以考虑在web.xml中定义其中的一个配置,并在其中使用@Import导入配置的其余部分。类似于:
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>com.example.config.AppConfig</param-value>
</context-param>@Configuration
@ComponentScan("foo.bar")
@Import({Config2.class, Config3.class})
public class AppConfig  {
    
}https://stackoverflow.com/questions/70741762
复制相似问题