使用Spring 5引导Web应用程序
翻译来源: Eugen Paraschiv 的 Bootstrap a Web Application with Spring 5
概述
本教程说明了如何使用Spring引导Web应用程序。
我们将研究Spring Boot解决方案以引导应用程序,还可以看到非Spring Boot方法。
我们主要使用Java配置,但也看看它们的等效XML配置。
使用Spring Boot引导
- Maven依赖
首先,我们需要spring-boot-starter-web依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
这个starter包括:
- 我们的Spring Web应用程序需要spring-web和spring-webmvc模块
- Tomcat启动器,以便我们可以直接运行我们的Web应用程序而无需显式安装任何服务器
- 创建一个Spring Boot应用程序
开始使用Spring Boot的最直接的方法,是创建一个主类,并使用@SpringBootApplication注解:
@SpringBootApplication
public class SpringBootRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRestApplication.class, args);
}
}
这一个注解@SpringBootApplication,等效于使用@Configuration,@EnableAutoConfiguration和@ComponentScan。
默认情况下,它将扫描同一个包及其子包中的所有组件。
然后对于基于Java的Spring beans配置,我们需要创建一个配置类并使用@Configuration注解:
@Configuration
public class WebConfig {
}
该注解是基于Java的Spring配置使用的主要组件; 它本身是使用@Component元注解的,它使注解类成为标准bean,因此也是组件扫描的候选者。
@Configuration类的主要目的是成为Spring IoC 容器的bean定义的源代码。 有关更详细的说明,请参阅官方文档。
让我们看看使用核心spring-webmvc库的解决方案。
使用spring-webmvc引导
- Maven依赖
首先,我们需要spring-webmvc依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.0.RELEASE</version>
</dependency>
- 基于Java的Web配置
接下来,我们将添加具有@Configuration批注的配置类:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.baeldung.controller")
public class WebConfig {
}
在这里,与Spring Boot解决方案不同,我们必须明确定义@EnableWebMvc以设置默认的Spring MVC配置,并使用@ComponentScan来指定要扫描组件的包。
@EnableWebMvc注解提供Spring Web MVC配置,例如设置前端控制器dispatcher servlet,启用@Controller和@RequestMapping注解以及设置其他默认值。
@ComponentScan配置组件扫描指令,指定要扫描的包。
- 初始化程序类
接下来,我们需要添加一个实现WebApplicationInitializer接口的类:
public class AppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.scan("com.baeldung");
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher =
container.addServlet("mvc", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
在这里,我们使用AnnotationConfigWebApplicationContext类创建一个Spring上下文,这意味着我们只使用基于注解的配置。 然后,我们指定要扫描组件和配置类的包。
最后,我们定义了Web应用程序的入口点 - DispatcherServlet。
此类可以完全替换Servlet 3.0 版本之前中的web.xml文件。
- XML配置
让我们快速浏览一下等效的XML Web配置:
<context:component-scan base-package="com.baeldung.controller" />
<mvc:annotation-driven />
我们可以用上面的WebConfig类替换这个XML文件。
要启动应用程序,我们可以使用加载XML配置的初始化程序类或web.xml文件。
- 总结
在本文中,我们研究了两种用于引导Spring Web应用程序的流行解决方案,一种使用Spring Boot Web启动程序,另一种使用核心spring-webmvc库。
在下一篇关于REST with Spring的文章中,我将介绍如何在项目中设置MVC,配置HTTP状态代码,有效负载编组和内容协商。
与往常一样,本文中提供的代码可以在Github上获得。 这是一个基于Maven的项目,因此它应该很容易导入和运行。