Spring Boot vs. Spring Framework: How They Compare

Spring Boot vs. Spring Framework: How They Compare

Spring Framework and Spring Boot are two popular Java-based frameworks used for building enterprise-level applications. Both frameworks provide a rich set of features for building scalable, resilient, and secure applications. However, they differ in their approach to configuration and ease of use. In this blog post, we'll compare Spring Framework and Spring Boot and highlight their differences.

Introduction

Let's start with an introduction to Spring Framework and Spring Boot.

What is Spring Framework?

Spring Framework is a mature framework that provides a comprehensive programming and configuration model for building Java applications. It provides a set of lightweight and loosely coupled components that can be easily integrated into applications. Some of the key features of Spring Framework are:

  • Inversion of Control (IoC): Spring Framework provides an IoC container that manages object dependencies and enables loose coupling between components.

  • Aspect-Oriented Programming (AOP): Spring Framework provides support for AOP, which enables modularization of cross-cutting concerns such as logging, security, and transaction management.

  • Data Access: Spring Framework provides support for interacting with databases using the Java Persistence API (JPA) and Object-Relational Mapping (ORM) frameworks such as Hibernate.

  • Web Framework: Spring Framework provides a web framework that enables building web applications using the Model-View-Controller (MVC) pattern.

  • Integration: Spring Framework provides support for integrating with other frameworks and technologies such as messaging systems, batch processing, and web services.

Here's an example of configuring Spring Framework's IoC container:

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

This creates a bean of type MyService and registers it with the IoC container.

What is Spring Boot?

Spring Boot is a lightweight framework that builds on top of Spring Framework and provides an opinionated way to configure Spring-based applications. It reduces the amount of boilerplate code required to configure Spring applications and enables faster development cycles. Some of the key features of Spring Boot are:

  • Auto-Configuration: Spring Boot provides a set of default configurations based on the application's dependencies. It automatically configures components such as the web server, database, and messaging systems based on the dependencies in the classpath.

  • Embedded Web Server: Spring Boot provides an embedded web server that enables running web applications without requiring an external web server.

  • Actuator: Spring Boot provides a set of endpoints that enable monitoring and management of the application at runtime. Endpoints include health checks, metrics, and environment variables.

  • DevTools: Spring Boot provides a set of tools that enable faster development cycles such as automatic restart of the application on code changes and live reloading of static resources.

Here's an example of configuring Spring Boot's embedded web server:

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

This starts a Spring Boot application with an embedded Tomcat web server.

Spring Framework vs. Spring Boot

Now that we've seen what Spring Framework and Spring Boot are, let's compare them based on some key features:

Ease of Use

When it comes to ease of use, Spring Boot is the clear winner. Spring Boot eliminates much of the boilerplate code that is required when building applications with the Spring Framework. Spring Boot provides auto-configuration, which means that it automatically configures the application based on the dependencies that are added to the project. This saves developers a lot of time and effort when it comes to configuring the application.

Here's an example of how easy it is to create a simple RESTful API with Spring Framework:

@Controller
@RequestMapping("/api")
public class MyController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public @ResponseBody String hello() {
        return "Hello World!";
    }
}

Here's an example of how easy it is to create a simple RESTful API with Spring Boot:

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello World!";
    }
}

Configuration

  • Spring Framework requires explicit configuration of components using Java configuration, XML configuration, or annotations.

  • Spring Boot provides auto-configuration based on the application's dependencies. It also provides a @SpringBootApplication annotation that combines several other annotations such as @Configuration, @EnableAutoConfiguration, and @ComponentScan.

Here's an example of configuring a datasource using Spring Framework:

@Configuration
public class AppConfig {
    @Bean
    public DataSource dataSource() {
        // create and configure DataSource
    }

    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }
}

Here's an example of configuring a datasource using Spring Boot:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

Security

  • Spring Framework provides support for securing web applications using its Spring Security module. It provides authentication, authorization, and session management features.

  • Spring Boot provides auto-configuration of Spring Security based on the application's dependencies. It also provides a set of starter dependencies for common security scenarios such as OAuth2 and JWT.

Here's an example of configuring Spring Security using Spring Framework (as well as Spring Boot):

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .and()
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("admin").password("{noop}password").roles("ADMIN")
                .and()
                .withUser("user").password("{noop}password").roles("USER");
    }
}

Data Access

  • Spring Framework provides support for interacting with databases using JPA, JDBC, and ORM frameworks such as Hibernate.

  • Spring Boot provides auto-configuration of data access based on the application's dependencies. It also provides a set of starter dependencies for common database systems such as MySQL, PostgreSQL, and MongoDB.

Here's an example of interacting with a database using Spring Framework:

@Repository
public class MyRepository {
    @Autowired
    private DataSource dataSource;

    public void save(MyEntity myEntity) {
        try (Connection connection = dataSource.getConnection();
             PreparedStatement statement = connection.prepareStatement("INSERT INTO my_table (id, name) VALUES (?, ?)")) {
            statement.setLong(1, myEntity.getId());
            statement.setString(2, myEntity.getName());
            statement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("Failed to save entity", e);
        }
    }
}

This code uses JDBC to interact with a database and insert an entity into a table. Here's an example of interacting with a database using Spring Boot:

@Repository
public interface MyRepository extends JpaRepository<MyEntity, Long> {
}

This code extends the JpaRepository interface provided by Spring Data JPA and provides basic CRUD operations for an entity.

Cloud

  • Spring Framework provides support for building cloud-native applications using its Spring Cloud project. It provides features such as service discovery, circuit breakers, and distributed tracing.

  • Spring Boot provides auto-configuration of Spring Cloud based on the application's dependencies. It also provides a set of starter dependencies for common cloud platforms such as AWS and Google Cloud.

Here's an example of using Spring Cloud Config in a Spring Framework application:

@Configuration
@EnableConfigServer
public class MyConfigServer {
    @Bean
    public GitPropertySourceLocator gitPropertySourceLocator(GitRepoFactory gitRepoFactory) {
        GitPropertySourceLocator locator = new GitPropertySourceLocator(gitRepoFactory);
        locator.setSearchLocations("file:./config-repo");
        return locator;
    }
}

This code enables the Spring Cloud Config Server and uses its default settings to store application configuration in a remote Git repository.

Here's an example of using Spring Cloud Config in a Spring Boot application:

@SpringBootApplication
@EnableConfigServer
public class MyConfigServer {
    public static void main(String[] args) {
        SpringApplication.run(MyConfigServer.class, args);
    }
}

The below configuration is required in application.properties file:

spring.cloud.config.server.git.uri=https://github.com/user/myconfigrepo.git

Overall, using Spring Cloud Config in a Spring Framework application requires a bit more setup than in a Spring Boot application, but the basic principles are the same. You need to configure a Spring Cloud Config Server to retrieve configuration properties from a Git repository, and then access those properties in your application using the @Value annotation. In Spring Boot, you can also use the @RefreshScope annotation to refresh your configuration properties at runtime.

RESTful APIs

  • Spring Framework provides support for building RESTful web services using its Spring MVC project. It provides features such as request mapping, content negotiation, and data binding.

  • Spring Boot provides auto-configuration of Spring MVC based on the application's dependencies. It also provides a set of starter dependencies for building RESTful APIs, including support for popular formats such as JSON and XML.

Microservices

  • Spring Framework provides features such as RESTful web services, message-driven architectures, and distributed transactions to build microservices.

  • Spring Boot provides a set of starter dependencies for building microservices, including support for Netflix OSS components such as Eureka (service discovery) and Hystrix (circuit breakers).

Here's an example of building a RESTful API using Spring Framework:

@RestController
@RequestMapping("/api")
public class MyController {
    @GetMapping("/greeting")
    public String getGreeting(@RequestParam(name = "name", defaultValue = "World") String name) {
        return "Hello, " + name + "!";
    }
}

This code defines a RESTful API endpoint that returns a greeting message based on a query parameter.

Here's an example of building a microservice using Spring Boot:

@SpringBootApplication
@EnableEurekaClient
public class MyMicroservice {
    public static void main(String[] args) {
        SpringApplication.run(MyMicroservice.class, args);
    }
}

This code defines a Spring Boot application that registers with a Eureka server as a client. This makes it discoverable by other microservices and provides features such as load balancing.

Conclusion

In conclusion, both Spring Framework and Spring Boot provide support for building cloud-native applications using Spring Cloud. Spring Framework requires you to add the relevant dependencies manually, while Spring Boot simplifies the process with auto-configuration and starter dependencies.

Did you find this article valuable?

Support Sujeet Kumar by becoming a sponsor. Any amount is appreciated!