How does SpringBoot decrease boiler plate code?

Viewed 2352

I understand how SpringBoot saves time in other respects such as having an embedded server and starter dependencies, but how does SpringBoot reduce boiler plate code needed for an application?

Thanks

4 Answers

Spring Boot brings a ton of autoconfiguration classes, which create beans with default configurations, that would have been created by the developer themselves previously. An example would be beans for database access. You would have created a datasource, maybe a JdbcTemplate, connection pool etc. Now those beans are created with autoconfiguration (example: https://github.com/spring-projects/spring-boot/blob/master/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java), and configuration can be customized through application.properties files.

You can look at Spring Boot as an opinionated distribution of Spring. It comes with sane defaults and machanisms to hide the boilerplate while still making changes to those defaults possible.

Spring boot comes with starters and through maven you can search for the required dependency and add it to your project it supports rapid development and below are some key features of spring boot

  • Removes boilerplate code of application setup by having embedded web server(Tomcat) and in memory db.
  • Auto configuration of application context.
  • Automatic servlet mappings.
  • Embedded database support(h2)
  • Automatic controller mapping

When you use annotations @SpringBootApplication, Spring boot takes care of creating all the beans required for running WebServer and injecting it using its Dependency Injection feature. @SpringBootApplication is alone equivalent to below three annotations.

  1. @Configuration : You can define your own configuration class to register your beans in application context.

2.@EnableAutoConfiguration : Spring automatically creates beans available on your classs path using this feature.More details are available here.

  1. @ComponentScan : Scans the current and base package where your application class lies.

It Creates ApplicationContext which contains all the necessary beans, ServletWebServerApplicationContext is one such bean created which takes care of initializing and running a WebServer by looking for ServletWebServerFactory bean(provides the webServer) within the ApplicationContext.
There is lot more going on behind the scene. Here is a video which explains it in details.

https://youtu.be/uCE3x4-GQ0k

https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/web/servlet/context/ServletWebServerApplicationContext.html

Related