What is the Difference between Spring Boot and Spring?
What is spring?
As a Java developer, everyone is familiar with Spring. In short, Spring Framework provides comprehensive infrastructure support for developing Java applications. It includes some nice functions, such as dependency injection and out-of-the-box modules, including Spring JDBC, Spring MVC, Spring Security, Spring AOP and Spring ORM, Spring Test.
These modules reduce the development time of applications and improve the efficiency of application development. For example, in the early stages of Java web development, we needed to write a lot of code to insert records into the database. However, we can simplify the operation in a few lines of code by using the JDBC Template of the Spring JDBC module.
Read Also – What are the Interview Questions for java?
What is Spring Boot?
Spring Boot is basically an extension of the Spring Framework. This eliminates the XML configuration required to set up Spring applications, leading to a faster and more efficient development ecosystem.
Read Also –
Spring Boot has the following features:
- Create a standalone Spring application
- Embedded Tomcat, Jetty, and Undertow containers (does not require war files).
- Provides simplified construction configuration of starters
- Configure Spring applications as automatically as possible
- Provide production indicators such as indicators, strong inspection and external configuration There are no code generation and XML configuration requirements at all.
Analyzing two frameworks from configuration
- Maven Dependencies
First, let’s take a look at the minimum dependencies required to build a web application using Spring:
<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>
Unlike Spring, Spring Boot only requires one dependency to start and run a Web application:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.6.RELEASE</version>
</dependency>
During build, all other dependencies are automatically added to the project.
Another good example is the test library. We commonly use Spring Test, JUnit, Hamcrest and Mockito libraries. In Spring projects, we should add all these libraries as dependencies. However, in Spring Boot, we just need to add the spring-boot-starter-test dependency to automatically include these libraries.
Spring Boot provides many dependencies for different Spring modules.
Some of the most commonly used dependencies are listed below:
spring- boot-starter-data-jpa
spring- boot-starter-security
spring- boot-starter- test
spring- boot-starter-web
spring- boot-starter-thymeleaf
For a complete list of starters, please see the Spring documentation.
- MVC Configuration
Let’s take a look at the configuration required for Spring and Spring Boot to create a JSP web application.
Spring needs to define scheduler servlets, mappings and other support configurations. We can do this using web.xml file or initializer class:
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.pingfangushi");
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = container
.addServlet("dispatcher", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
You also need to add the @EnableWebMvc annotation to the @Configuration class and define a view parser to parse the View returned from the controller:
@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;
}
}
Once we have added a Web launcher, Spring Boot only needs to configure several properties in the application configuration file to complete the operations above:
spring.mvc.view.prefix =/WEB-INF/jsp/
spring.mvc.view.suffix =.jsp
All of the above Spring configuration is automatically included by adding the Boot Web Starter through a process called auto-configuration.
This means that Spring Boot will review the dependencies, properties, and beans present in the application and configure the properties and beans according to these dependencies. If you want to add your custom configuration, Spring Boot auto-configuration will be reverted.
- Configure the template engine
Now, let’s see how to configure the Thymeleaf template engine in Spring and Spring Boot.
In Spring, we need to add the thymeleaf-spring5 dependency and some configuration for the view parser:
@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 Boot1x only requires the spring-boot-starter-thymeleaf dependency to enable thymeleaf support in web applications.
However, due to new features in Thymeleaf3.0, we need to add thymeleaf-layout-dialect as a dependency in SpringBoot2XWeb applications. After configuring the dependencies, we can add the templates to the src/main/resources/templates folder. Spring Boot will display them automatically.
- Configure Spring Security
For simplicity, we use the framework’s default HTTP Basic authentication. First, let’s take a look at the dependencies and configuration required to enable security using Spring.
Spring must depend on spring-security-web and spring-security-config modules. Next, we need to add a class that extends WebSecurityConfigurerAdapter and use the @EnableWebSecurity annotation:
@Configuration
@EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder()
.encode("password"))
.authorities("ROLE_ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Here, we use in memory authentication to set up authentication. Similarly, Spring Boot requires these dependencies to function. However, we only need to define the dependencies of spring-boot-starter-security as it will automatically add all the relevant dependencies to the class path.
The security configuration in Spring Boot is the same as above.
Application Launch Boot Configuration
The basic difference between application boot in Spring and Spring Boot is in the servlet. Spring uses web.xml or SpringServletContainerInitializer as its boot entry point.
Spring Boot only uses the Servlet 3 feature to boot applications. Let us know more about it.
2. Spring Boot Configuration
Spring supports the traditional Web.XML boot method and the latest Servlet 3+ method. To configure web.xml method startup:
- servlet container (server) reads web.xml
- The dispatcher servlet defined in web.xml is instantiated by the container.
- DispatcherServlet creates a WebApplicationContext by reading WEB-INF/{servletName}-servlet.xml.
Finally, the dispatcher registers the bean defined in the context of the servlet application. Spring startup steps using Servlet 3+ method. The container searches for classes that implement ServletContainerInitializer and executes SpringServeContainerInitializer to find classes that implement WebApplicationInitializer.
WebApplicationInitializer Creates a WebApplicationInitializer that contains an XML or @context configuration class that creates a DispatcherServlet with the previously created context.
- Spring Boot Configuration
The entry point for a Spring Boot application is a class annotated with @SpringBootApplication:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
By default, Spring Boot uses embedded containers to run applications. In this case, Spring Boot uses the public static void key entry point to start the embedded web server. Additionally, it is responsible for binding 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 classes in the same package or components in sub-packages of the main class.
Spring Boot provides a way to deploy it to an external container. We just need to extend SpringBootServletInitializer:
/**
* War deployment
*/
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(new HttpSessionEventPublisher());
}
}
Here, the external servlet container searches for the main class, which is defined in the MANIFEST.MF file of the META-INF folder under the war package.
SpringBootServletInitializer is responsible for binding the servlet, filter, and ServletContextInitializer.
Packaging and deployment
Finally, let’s look at how to package and deploy the application. Both frameworks support common package management technologies like Maven and Gradle. However, these frameworks differ in terms of deployment. For example, the Spring Boot Maven plugin provides Spring Boot support in Maven. It also allows an executable jar or war package to be packaged and run in place.
Spring Boot has the following advantages over Spring Boot in a deployment environment:
- Provides embedded container support
- Use java -jar command to run jar package independently
- When deploying to an external container, you can exclude dependencies to avoid potential jar conflicts
- Flexibility in specifying configuration file options at deployment time
- Random port generation for integration testing
conclusion
In short, we can say that Spring Boot is an extension of Spring, which makes development, testing and deployment more convenient.
Tag –
What is the Difference between Spring Boot and Spring?
What is the Difference between Spring Boot and Spring
Difference between Spring Boot and Spring?
Happy Learning…
- Dependency Track – End To End CI/CD Pipeline - November 29, 2024
- Dependency-track Jenkins Integration - November 27, 2024
- Jenkins Setup for PyTest + Selenium Automation Testing - November 27, 2024