Spring Framework — Recap Core Module

Sivakumar Ravichandran
5 min readJun 19, 2022
Spring

Spring framework

It is a comprehensive programming and configuration model that reduces the complexity of developing modern Java-based enterprise applications. A key element of Spring is infrastructural support at the application level. Teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Modules in Spring framework

In spring there are different modules available which are listed in the below image.

modules in spring framework

Benefits of Using Spring

  • It targets to make Jakarta EE development easier.
  • Lightweight
  • Inversion of Control (IoC) and Dependency Injection (DI)- Loosely coupled
  • Aspect Oriented Programming (AOP) - separation of business logic from system services
  • IoC container - manages bean lifecycle
  • MVC framework for web application
  • Transaction management of DB, File operations
  • Exception handling - technology-specific exceptions into consistent, unchecked exceptions

Inversion of Control

In traditional programming, where the program flow controls its execution, but in the IOC principle, the program delegates the control to something else like a Framework or Container which will drive the flow.

e.g. Strategy design pattern, Service Locator pattern, Factory pattern, and Dependency Injection (DI)

The advantages of this architecture are:

  • decoupling the execution of a task from its implementation
  • making it easier to switch between different implementations
  • greater modularity of a program
  • greater ease in testing a program by isolating a component or mocking its dependencies, and allowing components to communicate through contracts

Dependency Injection

It simply means that the class is no longer responsible for instantiating the objects it requires. Those responsibilities are passed to independent services.

Dependency injection involves four roles:

  • the service object(s) to be used
  • the client object that is depending on the service(s) it uses
  • the interfaces that defines how the client may use the services
  • the injector, which is responsible for constructing the services and injecting them into the client
dependency injection

Bean Injection

A bean is injected into another bean. It is done in three ways.

  • Setter Injection using <property> or @Autowired on setter method (Optional dependencies)
  • Constructor Injection using <constructor-arg> or @Autowired on constructor (Mandatory dependencies)
  • Field Injection uses @Autowired on a field without setter using Reflection API, (not recommended)

We can also provide a collection of beans as a list, set, map and properties.

Spring IoC Container

It implements IoC. It is responsible for instantiating, configuring and assembling objects known as Beans, as well as managing their life cycles.

It is represented by the interface ApplicationContext . There are three implementations of ApplicationContext

2 Standalone application contexts

  • ClassPathXmlApplicationContext
  • FileSystemXmlApplicationContext

1 Web application context

  • WebApplicationContext

Spring Bean

These are Java Objects that are initialized by the Spring IoC container. There a 5 Scopes for spring beans. They are

  • singleton (default) - one instance per IoC container
  • prototype - many instances per IoC container
  • request - one instance per HTTP request lifecycle
  • session - one instance per HTTP session lifecycle
  • global-session - one instance per HTTP session lifecycle (in the context of Portlet web application)

Generally, the spring beans are not thread-safe by default, implementation should take care of thread safety.

Bean Definition configuration (metadata)

Three ways of bean definition

  • XML-Based configuration
  • Annotation-Based configuration
  • Java-based configuration

In order to maintain the configuration, multiple configuration files are recommended which can be imported (<import> or @Import) in the main configuration.

lifecycle of different configurations

Bean Lifecycle

  1. Ioc Container instantiates beans from the bean definition configuration file.
  2. IoC populates properties
  3. Aware interfaces are called
    - if BeanNameAware interface is implemented, then calls setBeanName()
    - if BeanFactoryAware interface is implemented, then calls setBeanFactory()
    - if AppliactionContextAware interface is implemented, then calls setApplicationContext()
  4. If BeanPostProcessor is associated with the bean, then their postProcessBeforeInitialization is called in order
    - @PostConstruct
    - afterPropertiesSet() defined in InitializingBean
    - custom init-method definition
  5. If BeanPostProcessor is associated with the bean, then their postProcessAfterInitialization is called
  6. Bean is ready
  7. If the ApplicationContext is closed, then the destroy methods are called in order
    - @PreDestroy
    - destroy() defined in DisposableBean
    - custom destroy-method definition
bean life cycle
aware interface

A Simple Application to understand the bean lifecycle.

Bean wiring

IoC combines all beans together i.e. tie them together using Dependency Injection. There are different modes (autowire= attribute in <bean>)

  • no — default, specify by ref
  • byName - wires by name of the bean
  • byType - wires by class type
  • constructor - same as byType but applies to constructor arguments
  • autodetect - constructor or byType

There are also some limitations

  • Overriding possibility — by property and constructor-arg
  • Data types restriction — for Primitives, Strings, and Classes
  • Confusing Nature — hard to autowire when a lot of dependencies
  • inner beans which are declared in property cannot be reused

Bean Definition Template

A child bean definition inherits configuration from parent bean definition. Here child may override or add additional values.

If the parent bean definition is marked as abstract="true" and class attribute is not necessary, hence it cannot be instantiated.

Annotations

It relies on the bytecode metadata for wiring up components instead of angle-bracket declarations.

Wiring using Annotations

  1. @Resource - javax.annotation

The dependencies are resolved in the following order.

  • ByName
  • ByType
  • ByQualifier (@Qualifier in org.springframework.beans.factory.annotation)

2. @Autowired - org.springframework.beans.factory.annotation

The dependencies are resolved in the following order.

  • ByType
  • ByQualifier
  • ByName

3. @Inject - javax.inject

The dependencies are resolved same as @Autowired .

Lifecycle Hooks

There are 2 annotations for lifecycle hooks

  • @PostConstruct
  • @PreDestroy

Stereotype Annotations

These are special annotations defined based on the role in the application.

  • @Component - generic stereotype for Spring-managed component
  • @Repository for Data Access Object (DAO)
  • @Service
  • @Controller

Autodetect class for bean registration

  • done through component scanning
  • can add a custom filter for scanning
  • includeFilters and excludeFilters
  • include-filter and exclude-filter

AnnotationConfigApplicationContext

It is instantiated by @Configuration class or @Component class having bean definition and pass this class to the AnnotationConfigApplicationContext

Injecting inter-bean dependencies

We can pass one bean to another bean by calling the method in a Java-based configuration.

@Import annotation

We can even modularize the configuration separately.

Combining Java and XML configuration

We can do this in two ways.

XML-centric use of @Configuration classes

@Configuration class-centric use of XML with @ImportResource

References

--

--