java配置springmvc_Spring、SpringMVC版本及配置

java配置springmvc_Spring、SpringMVC版本及配置

一、Spring版本

Spring的最新版本是Spring 5.x,Spring 4.x的最后版本是Spring 4.4.x,会维护到2020年(Spring的GitHub主页对此有说明)。

二、SpringMVC

SpringMVC可以说是,应用了Spring的各种特性的一个MVC项目,它的核心Servlet是DispatcherServlet。

三、配置

各种Java框架一般都需要在web.xml中进行相关配置,一般都涉及到Listener、Filter、Servlet。

3.1 web.xml中配置

在Spring 3.1版本之前,在web.xml中配置DispatcherServlet是唯一的方式(同时声明映射):

dispatcher

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

/WEB-INF/spring/dispatcher-config.xml

1

dispatcher

/

**注释:load-on-startup is an integer value that specifies the order for multiple servlets to be loaded. So if you need to declare more than one servlet you can define in which order they will be initialized. Servlets marked with lower integers are loaded before servlets marked with higher integers.

3.2 web.xml和Java类中均可配置,即可混合配置

接下来,随着Servlet API 3.0的应用,web.xml中的配置不是必须的了,我们可以在Java类中配置DispatcherServlet:

public class MyWebAppInitializer implementsWebApplicationInitializer {

@Overridepublic voidonStartup(ServletContext container) {

XmlWebApplicationContext context= newXmlWebApplicationContext();

context.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");

ServletRegistration.Dynamic dispatcher=container

.addServlet("dispatcher", newDispatcherServlet(context));

dispatcher.setLoadOnStartup(1);

dispatcher.addMapping("/");

}

}

这里的Java配置类取得的最终效果与3.1节中的相同。

但是我们仍然使用了一个XML文件:dispatcher-config.xml

3.3 100%的Java配置

通过对3.2节中的Java配置类进行重构,我们无需再使用XML文件来配置Dispatcher:

public class MyWebAppInitializer implementsWebApplicationInitializer {

@Overridepublic voidonStartup(ServletContext container) {

AnnotationConfigWebApplicationContext context= newAnnotationConfigWebApplicationContext();

//context.register(AppConfig.class);

context.setConfigLocation("com.example.app.config");

container.addListener(newContextLoaderListener(context));

ServletRegistration.Dynamic dispatcher=container

.addServlet("dispatcher", newDispatcherServlet(context));

dispatcher.setLoadOnStartup(1);

dispatcher.addMapping("/");

}

}

**注释:

The first thing we will need to do is create the application context for the servlet.

This time we will use an annotation based context so that we can use Java and annotations for configuration and remove the need for XML files like dispatcher-config.xml.

3.4 总结

Spring 3.2及其以上的版本,均可以采用以上三种方式进行配置。

官方推荐纯Java类来配置,更加简洁和灵活。但是有时候必须XML文件也是无法避免的

四、SpringBoot化繁为简

这些配置很繁琐,SpringBoot就是达到一键生成的效果!

相关推荐

13个实用的WhatsApp在线登录技巧
365bet的网站是多少

13个实用的WhatsApp在线登录技巧

📅 09-07 👍 658
dnf升级一件b套要多久
365速发app下载平台注册

dnf升级一件b套要多久

📅 08-16 👍 178
《狂野飙车8》全面攻略(赛道技巧、装备升级与多人对战,玩转《狂野飙车8》的必备秘籍)