Reader small image

You're reading from  Modern API Development with Spring 6 and Spring Boot 3 - Second Edition

Product typeBook
Published inSep 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781804613276
Edition2nd Edition
Languages
Concepts
Right arrow
Author (1)
Sourabh Sharma
Sourabh Sharma
author image
Sourabh Sharma

Sourabh Sharma is a Senior Development Manager at Oracle with over 20 years of experience in the industry. He is a manager and architect who has been designing on-premise and cloud-based applications using Java, Javascript, and Oracle DB. Sourabh has worked with leading companies and delivered enterprise products and applications. His expertise lies in conceptualizing, modeling, designing, and developing N-tier and cloud-based web applications while leading teams. Sourabh's experience also includes developing microservice-based solutions and implementing various types of workflow and orchestration engines. He believes in continuous learning and sharing knowledge through his books and training.
Read more about Sourabh Sharma

Right arrow

Spring Concepts and REST APIs

In the previous chapter, we learned about the REST architecture style. Before we go and implement RESTful web services using Spring and Spring Boot, we need to have a proper understanding of the basic Spring concepts. In this chapter, you will learn about the Spring fundamentals and features that are required to implement RESTful web services using the Spring Framework. This will provide the technical perspective required for developing the example e-commerce app. If you are already aware of the Spring fundamentals required for implementing RESTful APIs, you can move on to the next chapter.

We’ll cover the following topics as part of this chapter:

  • Introduction to Spring
  • Understanding the basic concepts of the Spring Framework
  • Working with the servlet dispatcher

Technical requirements

This chapter covers concepts and does not involve writing actual code. However, you’ll need basic Java knowledge.

Please visit the following link to download the code files: https://github.com/PacktPublishing/Modern-API-Development-with-Spring-6-and-Spring-Boot-3/tree/main/Chapter02.

Understanding the patterns and paradigms of Spring

Spring is a framework written in the Java language. It provides lots of modules, such as Spring Data, Spring Security, Spring Cloud, Spring Web, and so on. It is popular for building enterprise applications. Initially, it was looked at as a Java Enterprise Edition (JEE) alternative. However, over the years, it has become preferred over JEE. Spring supports dependency injection (DI), also known as inversion of control (IoC), and aspect-oriented programming (AOP) out of the box at its core. Apart from Java, Spring also supports other JVM languages such as Groovy and Kotlin.

With the introduction of Spring Boot, the turnaround time for the development of web services was reduced. We can hit the ground running. This is huge and one of the reasons why Spring has become so popular lately.

Covering Spring fundamentals itself requires a dedicated book. I’ll try to be concise and cover all the features required for you to go ahead...

Understanding the application of IoC containers

The Spring Framework’s backbone is the IoC container that is responsible for a bean’s life cycle. In the Spring world, a Java object can be a bean if it is instantiated, assembled, and managed by the IoC container. You create a great number of beans, or objects, for your application. A bean may have dependencies that require other objects to work. The IoC container is responsible for injecting the object’s dependencies when it creates that bean. In the Spring context, IoC is also known as DI.

Note

You can refer to the Spring documentation (https://docs.spring.io/spring-framework/docs/current/reference/html/) for more information about the Spring Framework.

The Spring Framework’s IoC container core is defined in two packages: org.springframework.beans and org.springframework.context.

BeanFactory (org.springframework.beans.factory.BeanFactory) and ApplicationContext (org.springframework.context.ApplicationContext...

Defining a bean and its scope

Beans are Java objects that are managed by the IoC containers. The developer supplies the configuration metadata to an IoC container, which then uses the metadata to construct, assemble, and manage the beans. Each bean should have a unique identifier inside a container. A bean can even have more than one identity using an alias.

You can define beans using XML, Java, and annotations. Let’s declare a simple bean using a Java-based configuration:

public class SampleBean {  public void init() { // initialization logic }
  public void destroy() { // destruction logic }
  // bean code
}
public interface BeanInterface {
  // interface code
}
public class BeanInterfaceImpl implements BeanInterface
                {
  // bean code
}
@Configuration
public class AppConfig {
  @Bean(initMethod = "init", destroyMethod...

Configuring beans using Java

Before Spring 3, you could only define beans using XML. Spring 3 introduced the @Configuration, @Bean, @import, and @DependsOn annotations to configure and define Spring beans using Java.

You have already learned about the @Configuration and @Bean annotations in the Defining a bean and its scope section. Now, you will explore how to use the @Import and @DependsOn annotations.

The @Import annotation is more useful when you develop an application without using autoconfiguration.

The @Import annotation

@Import is used for modularizing configurations when you have more than one configuration class. You can import the bean’s definitions from other configuration classes, and this is useful when you instantiate the context manually. Spring Boot uses auto-configuration, so you don’t need to use @Import. However, you would have to use @Import to modularize the configurations if you want to instantiate the context manually.

Let’...

How to code DI

Have a look at the following example. CartService has a dependency on CartRepository. The CartRepository instantiation is done inside the CartService constructor:

public class CartService {  private CartRepository repository;
  public CartService() {
    this.repository = new CartRepositoryImpl();
  }
}

We can decouple this dependency in the following way:

public class CartService {  private CartRepository repository;
  public CartService(CartRepository repository) {
    this.repository = repository;
  }
}

If you create a bean of the CartRepository implementation, you can easily inject the CartRepository bean using configuration metadata. Before that, let’s have a look at the Spring container again.

You have seen how ApplicationContext can be initialized in the The @Import annotation subsection of this chapter. When it gets created, it takes all the...

Configuring a bean’s metadata using annotations

The Spring Framework provides lots of annotations to configure the metadata for beans. However, we’ll focus on the most used annotations: @Autowired, @Qualifier, @Inject, @Resource, @Primary, and @Value.

How to use @Autowired?

The @Autowired annotation allows you to define the configuration in a bean’s class itself, instead of writing a separate configuration class annotated with @Configuration.

The @Autowired annotation can be applied to a field (as we saw in the class property-based DI example), constructor, setter, or any method.

The Spring container makes use of reflections to inject the beans annotated with @Autowired. This also makes it more costly than other injection approaches.

Please make a note that applying @Autowired to class members will only work if there is no constructor or setter method to inject the dependent bean.

Here is a code example demonstrating the use of @Autowired to inject...

Writing code for AOP

We discussed AOP previously in the Understanding the patterns and paradigms of Spring section. In simple terms, AOP is a programming paradigm that solves cross-cutting concerns such as logging, transactions, and security. These cross-cutting concerns are known as aspects in AOP. They allow you to modularize your code and place cross-cutting concerns in a central location.

The following code captures the time taken by a method to execute:

class Test  public void performSomeTask() {
    long start = System.currentTimeMillis();
    // Business Logic
    long executionTime =
           System.currentTimeMillis() - start;
    System.out.println("Time taken: " + executionTime + "ms");
  }
}

Time calculations are used for monitoring performance. This code captures the execution time (how...

Why use Spring Boot?

Nowadays, Spring Boot is the obvious choice for developing state-of-the-art, production-ready web applications specific to Spring. Its website (https://projects.spring.io/spring-boot/) also outlines its huge advantages.

Spring Boot is an amazing Spring tool created by Pivotal that was released for General Availability in April 2014. It was developed based on the request of SPR-9888 (https://jira.spring.io/browse/SPR-9888) with the title Improved support for containerless web application architectures.

You might be wondering: why containerless? Because today’s cloud environment, with its Platform-as-a-Service (PaaS) offerings, provides most of the features offered by container-based web architectures, such as reliability, management, and scaling. Therefore, Spring Boot focuses on making itself an ultralight container.

Spring Boot has its own default configurations and also supports auto-configuration to make production-ready web application development...

Understanding the importance of servlet dispatcher

In the previous chapter, you learned that RESTful web services are developed on top of the HTTP protocol. Java has a Servlets feature to work with HTTP. Servlets allow you to have path mapping that can work at REST endpoints and provides the HTTP method for identification. Servlets also allow you to form different types of response objects, including JSON and XML. However, they offer a somewhat crude way of implementing REST endpoints, as you must still handle the request URI, parse the parameters, and convert JSON/XML and the responses on your own.

Spring MVC comes to your rescue. Spring MVC is based on the Model-View-Controller (MVC) pattern and has been part of the Spring Framework since its first release. MVC is a well-known design pattern:

  • Model: Models are Java objects (called POJOs) that contain the application data. They also represent the state of the application.
  • View: The view is a presentation layer that...

Summary

This chapter helped you learn about Spring’s key concepts: beans, DI, and AOP. You also learned how to define the scope of beans and create ApplicationContext programmatically, using it to get the beans. You can define beans’ configuration metadata using Java and annotations and have learned how to use different beans of the same type.

You also implemented an Aspect example, applying a module approach to a cross-cutting concern, and learned the key concepts of the AOP programming paradigm.

Since we are going to implement REST APIs in this book, it is important to understand the servlet dispatcher concept.

In the next chapter, we’ll implement our first REST API application using the OpenAPI Specification and use a Spring controller to implement it.

Questions

  1. How do you define a bean with the prototype scope?
  2. What is the difference between prototype and singleton beans?
  3. What is required for a session and request scope to work?
  4. What is the relationship between advice and pointcut in terms of AOP?
  5. Write an Aspect for logging that prints the method and argument names before the method execution, and prints a message with the return type (if any) after the method’s successful execution.

Answers

  1. By using the @Scope annotation as shown:
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  2. Beans defined using the singleton scope are instantiated only once per Spring container. The same instance is injected every time it is requested, whereas with a bean defined with the prototype scope, the container creates a new instance every time the injection is done by the Spring container for the requested bean. In short, a container creates a single bean per container for a singleton-scoped bean, whereas a container creates a new instance every time there is a new injection for prototype-scoped beans.
  3. Session and request scopes only work when a web-aware Spring context is used. Other scopes that also need a web-aware context to work are application and WebSocket scopes.
  4. Advice is an action taken by the Aspect at a specific time (JoinPoint). Aspects perform the additional logic (advice) at a certain point (JoinPoint), such as a method being called, an exception being...

Further reading

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Modern API Development with Spring 6 and Spring Boot 3 - Second Edition
Published in: Sep 2023Publisher: PacktISBN-13: 9781804613276
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Sourabh Sharma

Sourabh Sharma is a Senior Development Manager at Oracle with over 20 years of experience in the industry. He is a manager and architect who has been designing on-premise and cloud-based applications using Java, Javascript, and Oracle DB. Sourabh has worked with leading companies and delivered enterprise products and applications. His expertise lies in conceptualizing, modeling, designing, and developing N-tier and cloud-based web applications while leading teams. Sourabh's experience also includes developing microservice-based solutions and implementing various types of workflow and orchestration engines. He believes in continuous learning and sharing knowledge through his books and training.
Read more about Sourabh Sharma