1. Información general
En este artículo, veremos las diferencias entre los frameworks Spring estándar y Spring Boot.
Nos enfocaremos y discutiremos cómo los módulos de Spring, como MVC y Security, difieren cuando se usan en el núcleo de Spring y cuando se usan con Boot.
2. ¿Qué es la primavera?
En pocas palabras, el marco Spring proporciona un soporte de infraestructura integral para desarrollar aplicaciones Java .
Está repleto de algunas características interesantes como la inyección de dependencia y módulos listos para usar como:
- Primavera JDBC
- Primavera MVC
- Seguridad de primavera
- Primavera AOP
- ORM de primavera
- Prueba de primavera
Estos módulos pueden reducir drásticamente el tiempo de desarrollo de una aplicación.
Por ejemplo, en los primeros días del desarrollo web Java, necesitábamos escribir mucho código repetitivo para insertar un registro en una fuente de datos. Pero al usar JDBCTemplate del módulo Spring JDBC podemos reducirlo a unas pocas líneas de código con solo unas pocas configuraciones.
3. ¿Qué es Spring Boot?
Spring Boot es básicamente una extensión del marco Spring que eliminó las configuraciones estándar requeridas para configurar una aplicación Spring.
Adopta una visión obstinada de la plataforma Spring que allanó el camino para un ecosistema de desarrollo más rápido y eficiente .
Estas son solo algunas de las características de Spring Boot:
- Dependencias de 'principiante' con opiniones para simplificar la construcción y la configuración de la aplicación
- Servidor integrado para evitar la complejidad en la implementación de aplicaciones
- Métricas, verificación de estado y configuración externalizada
- Configuración automática para la funcionalidad Spring, siempre que sea posible
Familiaricémonos con ambos marcos paso a paso.
4. Dependencias de Maven
Primero que nada, veamos las dependencias mínimas requeridas para crear una aplicación web usando Spring:
org.springframework spring-web 5.2.9.RELEASE org.springframework spring-webmvc 5.2.9.RELEASE
A diferencia de Spring, Spring Boot requiere solo una dependencia para que una aplicación web esté en funcionamiento:
org.springframework.boot spring-boot-starter-web 2.3.4.RELEASE
Todas las demás dependencias se agregan automáticamente al archivo final durante el tiempo de compilación.
Otro buen ejemplo son las bibliotecas de prueba. Usualmente usamos el conjunto de bibliotecas Spring Test, JUnit, Hamcrest y Mockito. En un proyecto de Spring, deberíamos agregar todas estas bibliotecas como dependencias.
Pero en Spring Boot, solo necesitamos la dependencia de inicio para que las pruebas incluyan automáticamente estas bibliotecas.
Spring Boot proporciona una serie de dependencias de inicio para diferentes módulos Spring. Algunos de los más utilizados son:
- Spring-boot-starter-data-jpa
- Spring-boot-starter-security
- prueba de arranque de arranque de primavera
- Spring-boot-starter-web
- primavera-arranque-arranque-hoja de tomillo
Para obtener la lista completa de principiantes, consulte también la documentación de Spring.
5. Configuración MVC
Exploremos la configuración requerida para crear una aplicación web JSP usando Spring y Spring Boot.
Spring requiere definir el servlet del despachador, las asignaciones y otras configuraciones de soporte. Podemos hacer esto usando el archivo web.xml o una clase Initializer :
public class MyWebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) { AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.setConfigLocation("com.baeldung"); container.addListener(new ContextLoaderListener(context)); ServletRegistration.Dynamic dispatcher = container .addServlet("dispatcher", new DispatcherServlet(context)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }
También necesitamos agregar la anotación @EnableWebMvc a una clase @Configuration y definir un solucionador de vistas para resolver las vistas devueltas por los controladores:
@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; } }
En comparación con todo esto, Spring Boot solo necesita un par de propiedades para que las cosas funcionen, una vez que agregamos el iniciador web:
spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp
Toda la configuración de Spring anterior se incluye automáticamente al agregar el iniciador web Boot, a través de un proceso llamado configuración automática.
Lo que esto significa es que Spring Boot observará las dependencias, propiedades y beans que existen en la aplicación y habilitará la configuración basada en estos.
Por supuesto, si queremos agregar nuestra propia configuración personalizada, la configuración automática de Spring Boot retrocederá.
5.1. Configuración del motor de plantillas
Aprendamos ahora a configurar un motor de plantillas Thymeleaf tanto en Spring como en Spring Boot.
En Spring, necesitamos agregar la dependencia thymeleaf-spring5 y algunas configuraciones para el solucionador de vistas:
@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 1 solo requería la dependencia de spring-boot-starter-thymeleaf para habilitar el soporte de Thymeleaf en una aplicación web. Pero debido a las nuevas características de Thymeleaf3.0, tenemos que agregar thymeleaf-layout-dialect también como una dependencia en una aplicación web Spring Boot 2. Alternativamente, podemos optar por agregar una dependencia spring-boot-starter-thymeleaf que se encargará de todo esto por nosotros.
Once the dependencies are in place, we can add the templates to the src/main/resources/templates folder and the Spring Boot will display them automatically.
6. Spring Security Configuration
For the sake of simplicity, we'll see how the default HTTP Basic authentication is enabled using these frameworks.
Let's start by looking at the dependencies and configuration we need to enable Security using Spring.
Spring requires both the standard spring-security-web and spring-security-config dependencies to set up Security in an application.
Next, we need to add a class that extends the WebSecurityConfigurerAdapter and makes use of the @EnableWebSecurity annotation:
@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(); } }
Here we're using inMemoryAuthentication to set up the authentication.
Similarly, Spring Boot also requires these dependencies to make it work. But we need to define only the dependency ofspring-boot-starter-security as this will automatically add all the relevant dependencies to the classpath.
The security configuration in Spring Boot is the same as the one above.
If you need to know how the JPA configuration can be achieved in both Spring and Spring Boot, then check out our article A Guide to JPA with Spring.
7. Application Bootstrap
The basic difference in bootstrapping of an application in Spring and Spring Boot lies with the servlet. Spring uses either the web.xml or SpringServletContainerInitializer as its bootstrap entry point.
On the other hand, Spring Boot uses only Servlet 3 features to bootstrap an application. Let's talk about this in detail.
7.1. How Spring Bootstraps?
Spring supports both the legacy web.xml way of bootstrapping as well as the latest Servlet 3+ method.
Let's see the web.xml approach in steps:
- Servlet container (the server) reads web.xml
- The DispatcherServlet defined in the web.xml is instantiated by the container
- DispatcherServlet creates WebApplicationContext by reading WEB-INF/{servletName}-servlet.xml
- Finally, the DispatcherServlet registers the beans defined in the application context
Here's how Spring bootstraps using Servlet 3+ approach:
- The container searches for classes implementing ServletContainerInitializer and executes
- The SpringServletContainerInitializer finds all classes implementing WebApplicationInitializer
- The WebApplicationInitializer creates the context with XML or @Configuration classes
- The WebApplicationInitializer creates the DispatcherServlet with the previously created context.
7.2. How Spring Boot Bootstraps?
The entry point of a Spring Boot application is the class which is annotated with @SpringBootApplication:
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
By default, Spring Boot uses an embedded container to run the application. In this case, Spring Boot uses the public static void main entry-point to launch an embedded web server.
Also, it takes care of the binding of the Servlet, Filter, and ServletContextInitializer beans from the application context to the embedded servlet container.
Another feature of Spring Boot is that it automatically scans all the classes in the same package or sub packages of the Main-class for components.
Spring Boot provides the option of deploying it as a web archive in an external container as well. In this case, we have to extend the SpringBootServletInitializer:
@SpringBootApplication public class Application extends SpringBootServletInitializer { // ... }
Here the external servlet container looks for the Main-class defined in the META-INF file of the web archive and the SpringBootServletInitializer will take care of binding the Servlet, Filter, and ServletContextInitializer.
8. Packaging and Deployment
Finally, let's see how an application can be packaged and deployed. Both of these frameworks support the common package managing technologies like Maven and Gradle. But when it comes to deployment, these frameworks differ a lot.
For instance, the Spring Boot Maven Plugin provides Spring Boot support in Maven. It also allows packaging executable jar or war archives and running an application “in-place”.
Some of the advantages of Spring Boot over Spring in the context of deployment include:
- Provides embedded container support
- Provision to run the jars independently using the command java -jar
- Option to exclude dependencies to avoid potential jar conflicts when deploying in an external container
- Option to specify active profiles when deploying
- Random port generation for integration tests
9. Conclusion
En este tutorial, hemos aprendido las diferencias entre Spring y Spring Boot.
En pocas palabras, podemos decir que Spring Boot es simplemente una extensión de Spring para hacer que el desarrollo, las pruebas y la implementación sean más convenientes.