1. An overview of the

In this article, we’ll discuss the main value of Spring as one of the most popular Java frameworks.

Most importantly, we’ll try to understand why Spring is our framework of choice. The details of Spring and its components have been covered extensively in our previous tutorials. Therefore, we’ll skip the introductory “how” section and focus on the “why.”

2. Why use any framework?

Before we get into any discussion of Spring, let’s understand why we need to use any framework in the first place.

A general-purpose programming language like Java can support a wide variety of applications. Not to mention that Java is actively improving every day.

In addition, there are numerous open source and proprietary libraries that support Java in this regard.

So why do we need a framework at all? To be honest, using frameworks to accomplish tasks is not absolutely necessary. However, it is usually wise to use one for several reasons:

  • Help us focus on the core task, not the boilerplate associated with it
  • Years of wisdom in the form of design patterns
  • Help us comply with industry and regulatory standards
  • Reduce the total cost of ownership of your application

We’ve just scratched the surface, and we must say the benefits are hard to ignore. But it can’t be positive, so here’s what to watch out for:

  • It forces us to write applications a certain way
  • Bind to a particular version of the language and library
  • Resource occupation added to the application

Frankly, there are no silver bullets in software development and frameworks, and Java is certainly no exception. Therefore, the choice of which framework to use or not to use should depend on the context.

At the end of this article, we’ll make better decisions about Spring in Java.

3. A brief overview of the Spring ecosystem

Before we embark on a qualitative assessment of the Spring framework, let’s take a closer look at what the Spring ecosystem looks like.

Spring came along sometime in 2003, when Java Enterprise Edition was growing fast and developing enterprise applications was exciting, but also tedious!

Spring was originally an inversion of Control (IoC) container for Java. We still primarily associate Spring with it, and in fact it forms the core of the framework and other projects developed on top of it.

3.1. The Spring framework

The Spring framework is divided into modules, which makes it easy to choose which parts to use in any application:

  • Core: Provides Core features such as DI (dependency injection), internationalization, validation, and AOP (aspect oriented programming)
  • Data Access: Supports Data Access through JTA (Java Transaction API), JPA (Java Persistence API), and JDBC (Java database connection)
  • Web: Supports both the Servlet API (Spring MVC) and more recently the reactive API (Spring WebFlux), as well as WebSockets, STOMP, and WebClient
  • Integration: Supports Integration into enterprise Java via JMS (Java messaging Service), JMX (Java Management Extension), and RMI (Remote method invocation)
  • Testing: Support unit and integration Testing with mock objects, test appliances, context management, and caching

3.2. The Spring project

But more valuable to Spring is a strong ecosystem that has grown over the years and continues to grow. They are structured as Spring projects and are developed on top of the Spring framework.

While the list of Spring projects is long and constantly changing, there are a few things worth mentioning:

  • Boot: Provides us with a highly customized but extensible set of templates for creating various Spring-based projects with little or no time. It makes it very easy to create standalone Spring applications using embedded Tomcat or similar containers.
  • Cloud: Provides support to easily develop common distributed system patterns such as service discovery, circuit breakers, and API gateways. It helps us reduce the effort of deploying such boilerplate patterns on local, remote, and even hosted platforms.
  • Security: Provides a robust mechanism for developing authentication and authorization for Spring-based projects in a highly customizable manner. With minimal declarative support, we can gain protection against common attacks such as session fixation, click hijacking, and cross-site request forgery.
  • Mobile: Provides the ability to detect devices and adjust application behavior accordingly. In addition, device-aware view management is supported for optimal user experience, site preference management, and site switcher.
  • Batch: Provides a lightweight framework for developing Batch applications for enterprise systems such as data archiving. Intuitive support for scheduling, restart, skipping, metrics collection, and logging. In addition, scaling of high-volume jobs through optimization and partitioning is supported.

Needless to say, this is a fairly abstract introduction to what Spring has to offer. But it gives us enough of a foundation about Spring’s organization and breadth to discuss further.

4. The Spring operation

People are used to adding a Hello World program to learn about any new technology.

Let’s take a look at how Spring makes it easy to write a program that isn’t just Hello World. We will create an application that exposes CRUD operations as A REST API for a domain entity, such as an employee supported by an in-memory database. More importantly, we will use basic authentication to protect our mutation endpoints. Finally, no application can be truly completed without good, old unit tests.

4.1. Project Settings

We’ll set up a Spring Boot project using Spring Initializr, a handy online tool to Boot projects with the right dependencies. We will add Web, JPA, H2, and Security as project dependencies to get Maven configuration Settings correctly. More details are guided in one of our previous articles.

4.2. Domain model and persistence

Since there is little to do, we are ready to define the domain model and persistence.

Let’s start by defining Employee as a simple JPA entity:

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @NotNull
    private String firstName;
    @NotNull
    private String lastName;
    // Standard constructor, getters and setters
}
Copy the code

Notice that we include an automatically generated ID in the entity definition.

Now we must define the JPA repository for the entity. This is where Spring makes it very simple:

public interface EmployeeRepository 
  extends CrudRepository<Employee.Long> {
    List<Employee> findAll(a);
}
Copy the code

All we need to do is define such an interface, and Spring JPA will give us an implementation fleshed out with default and custom operations. Pretty neat! You can find more details about using Spring Data JPA in our other articles.

4.3. The controller

Now we must define a network controller to route and handle our incoming requests:

@RestController
public class EmployeeController {
    @Autowired
    private EmployeeRepository repository;
    @GetMapping("/employees")
    public List<Employee> getEmployees(a) {
        return repository.findAll();
    }
    // Other CRUD endpoints handlers
}
Copy the code

In fact, all we need to do is annotate this class and define the routing meta information and each handler method.

We discussed how to use the Spring REST controller in detail in our previous article.

4.4. Safety

So now that we’ve defined everything, how do we protect things like creating or deleting employees? We don’t want unauthenticated access to these endpoints!

Spring Security excels in this regard:

@EnableWebSecurity
public class WebSecurityConfig 
  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) 
      throws Exception {
        http
          .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/employees"."/employees/**")
            .permitAll()
          .anyRequest()
            .authenticated()
          .and()
            .httpBasic();
    }
    // other necessary beans and definitions
}
Copy the code

There are more details to understand here, but the most important one is that we only allow GET operations to be unrestricted declarative.

4.5. Test

Now we’ve done everything, but wait, how do we test this?

Let’s see if Spring makes it easier to write unit tests for REST controllers:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class EmployeeControllerTests {
    @Autowired
    private MockMvc mvc;
    @Test
    @WithMockUser(a)public void givenNoEmployee_whenCreateEmployee_thenEmployeeCreated(a) throws Exception {
        mvc.perform(post("/employees").content(
            new ObjectMapper().writeValueAsString(new Employee("First"."Last"))
            .with(csrf()))
          .contentType(MediaType.APPLICATION_JSON)
          .accept(MediaType.APPLICATION_JSON))
          .andExpect(MockMvcResultMatchers.status()
            .isCreated())
          .andExpect(jsonPath("$.firstName", is("First")))
          .andExpect(jsonPath("$.lastName", is("Last")));
    }
    // other tests as necessary
}
Copy the code

As we can see, Spring provides us with the necessary infrastructure to write simple unit and integration tests that would otherwise depend on the Spring context to initialize and configure.

4.6. Run the application

Finally, how do we run this application? This is another interesting aspect of Spring Boot. Although we can package it as a regular application and traditionally deploy it on a Servlet container.

But what fun is that?! Spring Boot comes with an embedded Tomcat server:

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

This is a pre-created class that, as part of the bootstrap, has all the necessary details to launch the application using an embedded server.

Plus, it’s highly customizable.

5. Alternatives to Spring

While choosing to use a framework is relatively easy, choosing between frameworks often makes the choice difficult. To do this, however, we must take at least a cursory look at what alternatives Spring provides.

As mentioned earlier, the Spring framework and its projects offer enterprise developers a wide range of options. If we do a quick evaluation of contemporary Java frameworks, they don’t even compare to the ecosystem Spring provides us.

However, for specific areas, they do form a compelling argument for choosing alternatives:

  • Guice: Provides a robust IoC container for Java applications
  • Play: Ideally suited as a Responsive Web framework
  • Hibernate: A data access framework based on JPA support

In addition to these, there are some new features that offer broader support than specific domains, but still don’t cover everything Spring has to offer:

  • Micronaut: A JVM-based framework customized for cloud native microservices
  • Quarkus: A new-age Java stack that promises faster startup times and a smaller footprint

Obviously, completely iterating through this list is neither necessary nor feasible, but we get the broad idea here.

6. Why do you choose Spring?

Finally, we built all the necessary contexts to solve our core question, why Spring? We understand the ways in which frameworks can help us develop complex enterprise applications.

In addition, we understand the choices we make on specific issues, such as the Web, data access, integration with frameworks, and Java in particular.

Now, in all of this, where does Spring shine? Let’s explore.

6.1. Availability

A key aspect of the popularity of any framework is how easy it is for developers to use it. Spring makes it easy for developers to start up with multiple configuration options and convention over configuration, and then configure exactly what they need.

Projects like Spring Boot make it easy to Boot a complex Spring project. Not to mention, it has excellent documentation and tutorials to help anyone get started.

6.2. Modular

Another key aspect of Spring’s popularity is its highly modular nature. We can choose to use the entire Spring framework or just the necessary modules. In addition, we can choose to include one or more Spring projects as needed.

Also, we can choose to use another framework like Hibernate or Struts!

6.3. The consistency

While Spring does not support all Java EE specifications, it does support all technologies, often improving support for standard specifications when necessary. For example, Spring supports jPA-based repositories, so switching providers becomes trivial.

In addition, Spring supports industry specifications such as Reactive Stream under Spring Web Reactive and HATEOAS under Spring HATEOAS.

6.4. Testability

Adopting any framework also depends largely on how easy it is to test applications built on top of it. At its core, Spring advocates and supports test-driven development (TDD).

Spring applications are mostly composed of POJOs, which naturally makes unit testing much simpler. However, Spring does provide Mock objects for scenarios such as MVC, otherwise unit testing becomes complicated.

6.5. Mature

Spring has a long history of innovation, adoption, and standardization. Over the years, it has matured enough to become the default solution to the most common problems in large enterprise application development.

Even more exciting is the active development and maintenance. Support for new language features and enterprise integration solutions is being developed every day.

6.6. Community support

Last but not least, any framework or even class library survives the industry through innovation, and there is no better place to innovate than the community. Spring is open source Software led by Pivotal Software and supported by large organizations and individual developers.

That means it remains contextual and often futuristic, as is evident from the number of projects under its umbrella.

7. Reasons for not using Spring

There are a variety of applications that can benefit from using Spring at different levels, and those applications are changing just as fast as Spring is growing.

However, we must understand that Spring, like other frameworks, helps manage the complexity of application development. It helps us avoid common pitfalls and keeps the application maintainable over time.

This comes at the cost of an additional resource footprint and learning curve, however small it may be. If there really is an application that is simple enough and not expected to get complicated, it may be more beneficial to not use any framework at all!

Conclusion 8.

In this article, we discussed the benefits of using frameworks in application development. We also discussed the Spring framework briefly.

In discussing this topic, we also looked at some alternative frameworks available for Java.

Finally, we discussed what prompted us to choose Spring as the Java selection framework.

However, we should give some suggestions at the end of this article. As compelling as it sounds, there is often no single, one-size-fits-all solution in software development.

Therefore, we must use our wisdom and choose the simplest solution for the specific problem we are trying to solve.


I have translated the articles into PDF recently.

Reply in the public account background: 002 can be picked up oh ~

The content of PDF will be updated in the future, please look forward to it!