1.SpringBoot:简述SpringBoot和Spring的区别
1.1
Spring的介绍
简而言之,Spring框架为开发Java应用程序提供了全面的基础架构支持。它包含一些很好的功能,如依赖注入和开箱即用的模块,如:
- Spring JDBC
- Spring MVC
- Spring Security
- Spring AOP
- Spring ORM
- Spring Test
这些模块可以大大缩短应用程序的开发时间。例如,在Java Web开发的早期阶段,我们需要编写大量的重复代码来将记录插入到数据源中。但是通过使用Spring JDBC模块的JDBCTemplate,我们可以将它简化为只需几个简单配置或者几行代码。
2.SpringBoot的介绍
Spring Boot基本上是Spring框架的扩展,它消除了设置Spring应用程序所需的复杂例行配置。
它的目标和Spring的目标是一致的,为更快,更高效的开发生态系统铺平了道路。以下是Spring Boot中的一些功能:
- 通过starter这一个依赖,以简化构建和复杂的应用程序配置。
- 可以直接main函数启动,嵌入式web服务器,避免了应用程序部署的复杂性,Metrics度量,Helth check健康检查和外部化配置。
- 尽可能的自动化配置Spring功能。
三、Spring与SpringBoot的比较
3.1 Maven依赖
首先,让我们看一下使用Spring创建Web应用程序所需的最小依赖项:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
与Spring不同,Spring Boot只需要一个依赖项来启动和运行Web应用程序:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>
在构建期间,所有其他依赖项将自动添加到最终归档中。
Spring Boot为不同的Spring模块提供了许多入门依赖项。一些最常用的是:
- spring-boot-starter-data-jpa
- spring-boot-starter-security
- spring-boot-starter-test
- spring-boot-starter-web
- spring-boot-starter-thymeleaf
3.2 MVC配置
下面来探讨一下使用Spring和Spring Boot创建JSP Web应用程序所需的配置。
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.test.package");
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
我们还需要将@EnableWebMvc注解添加到@Configuration注解类,并定义一个视图解析器来解析从控制器返回的视图:
@EnableWebMvc
@Configuration
public class ClientWebConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}
与所有这些相比,一旦我们添加了Spring boot web starter,Spring Boot只需要一些属性来使上面的事情正常工作:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
- 上面的所有Spring配置都是通过一个名为auto-configuration的进程添加Boot web starter来自动包含的。
这意味着Spring Boot将自动扫描应用程序中存在的依赖项,属性和bean,并根据这些内容启用相应的配置。
3.3 模板引擎配置
再来看看如何在Spring和Spring Boot中配置Thymeleaf模板引擎,两者有啥区别?
在Spring中,我们需要为视图解析器添加 thymeleaf-spring5依赖项和一些配置:
@Configuration
@EnableWebMvc
public class MvcWebConfig implements WebMvcConfigurer {
@Autowired
private ApplicationContext applicat