Skip to main content

Spring Design Patterns

Java Spring Design Patterns

Java Spring Concepts Reference

IoC (Inversion of Control) and DI (Dependency Injection)

Lets review Concepts of IoC (Inversion of Control) and DI (Dependency Injection),

  • IoC Inversion of Control is a principle in software design which transfers the control of object instance lifecycles to a container.

  • Dependency Injection is a pattern used to implement IoC, where the control that is inverted is provisioning object's dependencies by container rather than object itself. So injecting object dependecies into other objects is done by an outside assembler rather than by the individual objects.

  • In Spring, The interface ApplicationContext is used to support or implement the IoC container. The Spring IoC container is responsible for instantiating & configuring beans and managing their life cycles.

  • DI (Dependency Injection) Options

    • Use Constructor based injection for mandatory dependencies.
    • Can use Setter based injection for optional dependencies.

Example:

  • The @Configuration annotation is used on the class having source of bean definitions.
  • The @Bean annotation on a method will define it as a bean. With method name as bean name.

IoC DI usage examples

  • Configuration
@Configuration
public class EmKafkaEventsConfig {

@Value("${spring.kafka.topic.name}")
private String topicName;

@Bean
public NewTopic topic() {
return TopicBuilder.name(topicName).build();
}

}
  • Field-Based Dependency Injection - @Autowired
@RestController 
public class CustomerDataRestController {

@Autowired
private CustomerService customerService;
  • Constructor-Based Dependency Injection
@RestController 
public class CustomerDataRestController {

private CustomerService customerService;

public CustomerDataRestController(CustomerService customerService) {
this.customerService = customerService;
}

Spring Boot APIs Design Patterns

Singleton Pattern

In Java: a singleton is one instanace per application In Spring: A singleton is one object instance per Spring IoC container. (One per application context).

Bean Scopes

  • Spring creates all beans as singletons by default.

  • Define Bean scopes to change this behavior.

    • singleton @Scope("singleton")
      • The container creates a single instance of the bean and it is cached. Any requests for that bean will return the same instance.
    • prototype @Scope("prototype")
      • return a new instance every time bean request made to container

    Note: Below scopes for use in Web aware Application Context

    • request - Use as @RequestScope
      • create a bean instance for each HTTP request
    • session = Use as @SessionScope
      • create a bean instance for each session, multiple HTTP request within a session get same instance.
    • application (Not used in our generated code)
      • creates the bean instance for a ServletContext.
    • websocket @Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
      • Creates for each WebSocket session and the same bean is returned during the entire WebSocket session.

Factory Pattern

  • The factory pattern uses a factory class with an abstract method for creating the different desired object.
  • Add factory implementation with concrete factory method for each desired object to be created. e.g.
public interface Animal {
void makesSound();
}
public class Bird implements Animal {
@Override
public void makesSound() {
System.out.println("Bird chirping");
}
}
public class Dog implements Animal {
@Override
public void makesSound() {
System.out.println("Dog barking");
}
}

Abstract Factory Pattern

  • Abstract Factory is a creational design pattern, e.g. in products, helps in creating entire product families without specifying their concrete classes. Abstract Factory defines an interface for creating all distinct products and implements concrete factory classes for the actual product creation.

Builder Pattern

  • Builder is a creational design pattern, helping in constructing complex objects step by step. Allowing taking care of individuals variations in building object of required type.
  • It will have Director, Builder interface, and ConcreteBuilders per object variation type.
  • e.g. Bilding Computers as per different RAM, HD, GrpahicsCard, etc. for Desktops or Laptops. ComputerBuilder buildComputer() : DesktopBuilder, NotebookBuilder, ...

Proxy pattern

  • The proxy pattern implements a way that defines one object as the proxy and it can refer to another object during runtime.
  • e.g. @Transactional annotation in Spring uses internally proxy Bean (e.g. EnhancerBySpringCGLIB) that wraps Repository bean to ensure transactional consistency.

Template pattern

  • The template pattern helps to reduce boilerplate code and taking care of series of steps but leaving the customizable steps as abstract. Subclasses can provide a concrete implementation for the abstract classes.
  • e.g. spring Java Persistence API (JPA) classes

External Configuration

  • can be used to completely change application flow or behavior based on external configuration.