如何在旧的web.xml中使用@Configuration引导spring应用程序?假设我正在用@Configuration@ComponentScan注释样式构建一个spring项目,那么我如何让它与web.xml一起工作呢?从哪里开始配置类?我确实尝试了以下代码,但似乎不起作用。
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);
}
}
main方法从未被调用过,知道吗?
基本上,您需要将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 {
}