1.Maven依赖
以web为例,让我们看一下使用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
2.MVC配置
使用spring时,
方式1:在web.xml中配置DispatcherServlet,在springmvc中配置视图解析器等
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>1.SpringMVC_helloworld</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- SpringMVC思想是有一个前端控制器能拦截所有请求,并智能派发;
这个前端控制器是一个servlet;应该在web.xml中配置这个servlet来拦截所有请求
-->
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- contextConfigLocation:指定SpringMVC配置文件位置 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- servlet启动加载,servlet原本是第一次访问创建对象;
load-on-startup:服务器启动的时候创建对象;值越小优先级越高,越先创建对象;
-->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<!--
/*和/都是拦截所有请求; /:会拦截所有请求,但是不会拦截*.jsp;能保证jsp访问正常;
/*的范围更大;还会拦截到*.jsp这些请求;一但拦截jsp页面就不能显示了;
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<!-- 视图解析器,可以简化方法的返回值,返回值就是作为目标页面地址,
只不过视图解析器可以帮我们拼串
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
在springboot中,添加了Spring boot web starter后,Spring Boot只需要一些属性来使上面的事情正常工作:
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
方式2:
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;
}
}
SpringBoot拥有自动配置功能,SpringBoot在启动时会自动加载所有配置类,根据依赖项中类的条件配置类生效,如DispatcherServlet组件;并默认都会绑定配置文件指定的值,从xxxxProperties里面拿,xxxProperties和配置类进行了绑定,如视图解析器。
3.模板引擎配置
再来看看如何在Spring和Spring Boot中配置Thymeleaf模板引擎,两者有啥区别?
在Spring中,我们需要为视图解析器添加 thymeleaf-spring5依赖项和一些配置
@Configuration
@EnableWebMvc
public class MvcWebConfig implements WebMvcConfigurer {
@Autowired
private ApplicationContext applicationContext;
@Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
registry.viewResolver(resolver);
}
}
Spring Boot 只需要spring-boot-starter-thymeleaf的依赖项 来启用Web应用程序中的Thymeleaf支持。 一旦依赖关系添加成功后,我们就可以将模板添加到src / main / resources / templates文件夹中,Spring Boot将自动显示它们。
4.安全配置
为简单起见,我们将看到如何使用Spring和Spring Boot框架启用默认的HTTP Basic身份验证。
让我们首先看一下使用Spring启用Security所需的依赖关系和配置。
Spring需要标准的 spring-security-web和spring-security-config 依赖项来在应用程序中设置Security。 接下来, 我们需要添加一个扩展WebSecurityConfigurerAdapter的类,并使用@EnableWebSecurity注解:
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1")
.password(passwordEncoder().encode("user1Pass"))
.authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Spring Boot也需要这些依赖项才能使其工作。但是我们只需要定义spring-boot-starter-security的依赖关系,它会自动将所有相关的依赖项添加到类路径中。
5.应用引导Application Bootstrap
Spring和Spring Boot中应用程序引导的基本区别在于servlet。Spring使用web.xml 或SpringServletContainerInitializer 作为其引导入口点。spring boot仅仅使用Servlet 3来引导程序。
1.首先来说说spring引导
方法一:web.xml引导方法
Servlet容器(服务器)读取web.xml
web.xml中定义的DispatcherServlet由容器实例化
DispatcherServlet通过读取WEB-INF / {servletName} -servlet.xml来创建WebApplicationContext
最后,DispatcherServlet注册在应用程序上下文中定义的bean
方法二:servlet 3+引导方法
容器搜索实现ServletContainerInitializer的 类并执行
SpringServletContainerInitializer找到实现类WebApplicationInitializer的子类
WebApplicationInitializer创建会话使用XML或上下文@Configuration类
WebApplicationInitializer创建DispatcherServlet,使用先前创建的上下文。
2.再来说说Spring Boot引导
Spring Boot应用程序的入口点是使用@SpringBootApplication注释的类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
默认情况下,Spring Boot使用嵌入式容器来运行应用程序。在这种情况下,Spring Boot使用public static void main入口点来启动嵌入式Web服务器。此外,它还负责将Servlet,Filter和ServletContextInitializer bean从应用程序上下文绑定到嵌入式servlet容器。
Spring Boot的另一个特性是它会自动扫描同一个包中的所有类或Main类的子包中的组件。
Spring Boot提供了将其部署为外部容器中的Web存档的选项。在这种情况下,我们必须扩展SpringBootServletInitializer:
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
// ...
}
外部Servlet容器查找在Web归档文件的META-INF文件中定义的Main-class,SpringBootServletInitializer将负责绑定Servlet,Filter和ServletContextInitializer
6.打包和部署
最后,让我们看看如何打包和部署应用程序。这两个框架都支持Maven和Gradle等常见的包管理技术。但是在部署方面,这些框架差异很大。例如,Spring Boot Maven插件在Maven中提供Spring Boot支持。它还允许打包可执行jar或war档案并“就地”运行应用程序。
与spring相比,在部署环境中Spring Boot的一些优点包括
- 提供嵌入式容器支持
- 使用命令java -jar独立运行jar
- 在外部容器中部署时,可以选择排除依赖关系以避免潜在的jar冲突
- 部署时灵活指定配置文件的选项
- 用于集成测试的随机端口生成