介紹
本篇文章主要介紹,如何使用 Spring 開發一個 Web 應用。
我們將研究用 Spring Boot 開發一個 web 應用,並研究用非 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>
該依賴包含:
- Spring Web 應用程序所需的 spring-web 和 spring-webmvc 模塊
- Tomcat 容器,這樣我們就可以直接運行 Web 應用程序,而無需安裝 Tomcat
創建一個Spring Boot 應用程序
使用 Spring Boot 的最直接的方法是創建一個主類,並添加 @SpringBootApplication 註解:
@SpringBootApplication
public class SpringBootRestApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRestApplication.class, args);
}
}
此單個註釋等效於使用 @Configuration ,@EnableAutoConfiguration 和 @ComponentScan 。
默認情況下,它將掃描本包和它的子包中的所有組件。
接下來,對於基於 Java 的 Spring Bean 配置,我們需要創建一個配置類,並使用 @Configuration 註解:
@Configuration
public class WebConfig {
}
該註解是 Spring 主要使用的配置。 它本身使用 @Component 進行元註解,這使註解的類成爲標準 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
@EnableWebMvc
@ComponentScan(basePackages = "com.qulingfeng.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.qulingfeng");
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher =
container.addServlet("mvc", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
在這裏,我們使用 AnnotationConfigWebApplicationContext 類創建 Spring 上下文,這意味着我們僅使用基於註釋的配置。 然後,我們指定要掃描組件和配置類的包。
最後,我們定義 Web 應用程序的入口點 — DispatcherServlet 。
此類可以完全替換 < 3.0 Servlet 版本中的 web.xml 文件。
XML配置
讓我們快速看一下等效的XML web配置:
<context:component-scan base-package="com.qulingfeng.controller" />
<mvc:annotation-driven />
我們可以用上面的 WebConfig 類替換這個 XML 文件。
要啓動應用程序,我們可以使用一個初始化器類來加載 XML 配置或 web.xml 文件。
結束語
在篇文章中,我們研究了兩種用於開發 Spring Web 應用程序的流行方式,一種使用 Spring Boot Web 啓動程序,另一種使用核心 spring-webmvc 庫。
歡迎關注我的公衆號:曲翎風,獲得獨家整理的學習資源和日常乾貨推送。
如果您對我的專題內容感興趣,也可以關注我的博客:sagowiec.com