Spring Framework: Basics, IoC container, Dependency Injection (DI), Beans & AOP

Spring Framework: Basics, IoC container, Dependency Injection (DI), Beans & AOP

Background:

The Spring Framework is a comprehensive and versatile framework for building enterprise-grade, robust, scalable and modular backend applications for powering businesses of all types. One of the main reasons for favouring Spring Framework over any other backend framework is due to it's large ecosystem, diverse set of testing, tools & libraries and strong community support, which helps maintain and manage lifecycle of any enterprise-level open-source software project or framework.

Ecosystem:

Spring is a very large ecosystem, which means you can build any type of backend for your software product; RESTful, GraphQL, SOAP services, MVC web, event-driven systems (such as Kafka & RabbitMQ), high concurrent non-blocking (multi-threaded) applications (Webflux, Netty, Reactor), distributed micro-services (Spring Cloud, Eureka, Gateway, Load Balancer), observability (Zipkin, Prometheus, Dynatrace), data persistence and caching (Spring Redis, JPA, JDBC, Cassandra), security (Spring Security, OAuth) and many other types of backend applications. So it's better to start with the basics of framework first, learn it and then getting a high-level idea about putting that in use.

Core Concepts:

Inversion of Control (IoC)

Definition: IoC is a software design principle in which the control of object creation, configuration, and management is transferred from the application code to the framework. Spring IoC container is responsible to inject, control and manage lifecycle of objects giving developer more flexibility to focus more on writing business logic code.

Dependency Injection (DI)

Spring implements IoC through Dependency Injection (DI), where dependencies are injected into objects rather than objects creating their own dependencies.

Types:

  • Constructor Injection: Dependencies are provided through the constructor.
  • Setter Injection: Dependencies are provided through setter methods.
  • Field Injection: Dependencies are injected directly into the fields (using annotations)

Spring Core Container:

Beans

Definition: In Spring, the objects that form the backbone of your application and are managed by the Spring IoC container are called beans.

Configuration: Beans can be defined in XML configuration files, annotated classes, or Java configuration classes.

Scopes:

  • Singleton: (Default) A single instance per Spring IoC container.
  • Prototype: A new instance every time a bean is requested.
  • Request: A single instance per HTTP request (Web applications only).
  • Session: A single instance per HTTP session (Web applications only).
  • Global Session: A single instance per global HTTP session (Portlet-based web applications).

Lifecycle:

  • Instantiation: The bean is created.
  • Property Population: Dependencies are injected.
  • Initialization: Custom initialization methods can be called (@PostConstruct, InitializingBean).
  • Destruction: Bean is destroyed (@PreDestroy, DisposableBean).


ApplicationContext

Definition: The ApplicationContext interface represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans.

Common Implementations:

  • ClassPathXmlApplicationContext: Loads context definition from an XML file located in the classpath.
  • FileSystemXmlApplicationContext: Loads context definition from an XML file located in the file system.
  • AnnotationConfigApplicationContext: Loads context from annotated classes and Java-based configuration.


AOP (Aspect Oriented Programming)

Definition: Spring AOP is a powerful feature of the Spring Framework that enables separation of cross-cutting concerns, such as logging, security, and transaction management, from the main business logic of an application. AOP allows developers to define additional behaviour that should be applied to various points in an application's execution, known as join points, without modifying the core logic of the application.

Aspect

Definition: An aspect is a module that encapsulates a concern that cuts across multiple classes. Aspects can contain multiple advices.

Example: A logging module that captures log information across different methods in different classes.

Advice

Definition: Advice is the action taken by an aspect at a particular join point. Different types of advice include:

  • Before Advice: Executed before a join point.
  • After Advice: Executed after a join point, regardless of the outcome.
  • After Returning Advice: Executed after a join point completes normally.
  • After Throwing Advice: Executed if a method exits by throwing an exception.
  • Around Advice: Surrounds a join point, allowing the advice to perform custom behavior before and after the method invocation.

Join Point

  • Definition: A join point is a specific point in the execution of a program, such as a method execution or exception handling.
  • Example: Any method execution in a class can be a join point where advice can be applied.

@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
    System.out.println("Method called: " + joinPoint.getSignature().getName());
}        

Pointcut

  • Definition: A pointcut is an expression that matches join points. It determines whether a piece of advice should be executed.

@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceLayer() {}        

Proxy

  • Definition: A proxy is an object created by the AOP framework to control access to the target object. Proxies can be created using JDK dynamic proxies or CGLIB proxies.
  • Example: When a method is called on a proxy, the proxy can intercept the call and apply the aspect's advice before invoking the target method.


How Spring AOP works

a. Proxy-Based AOP

  • Dynamic Proxies (JDK Proxies): Used when the target object implements at least one interface. A proxy is created that implements the same interfaces as the target object.
  • CGLIB Proxies: Used when the target object does not implement any interfaces. A subclass proxy is created using CGLIB (Code Generation Library).

b. Weaving

  • Definition: Weaving is the process of applying aspects to a target object to create an advised object. In Spring, weaving is performed at runtime.
  • Types of Weaving:Compile-Time Weaving: Aspects are woven into the code at compile time.Load-Time Weaving: Aspects are woven into the code when the class is loaded.Runtime Weaving: Aspects are woven into the code at runtime using proxies (the approach used by Spring AOP).


Spring AOP Use Cases

a. Logging

  • Implement cross-cutting logging logic that applies to multiple methods and classes.

@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
    System.out.println("Method called: " + joinPoint.getSignature().getName());
}        

b. Security

  • Apply security checks before method execution.

@Before("execution(* com.example.service.*.*(..)) && @annotation(com.example.security.Secured)")
public void checkSecurity(JoinPoint joinPoint) {
    // Perform security checks
}        

c. Transaction Management

  • Manage transactions declaratively using AOP.

@Transactional
public void performTransaction() {
    // Business logic with transaction management
}        

Summary

Understanding these core concepts of the Spring Framework is essential for building scalable and maintainable backend applications. The focus on IoC and DI leads to a modular architecture, while the robust configuration and management provided by ApplicationContext and Spring Beans ensure efficient application development, lifecycle and operability.

Syed Naashit Ali

React Native Mobile Application Developer | Building Robust Cross-Platform Apps @ TAFSOL Technologies

7 个月

Well said! ??

要查看或添加评论,请登录

Shehroz Ali的更多文章

社区洞察

其他会员也浏览了