Spring Framework — Recap Core Module
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.
Benefits of Using Spring
- It targets to make Jakarta EE development easier.
Lightweight
Inversion of Control
(IoC) andDependency Injection
(DI)- Loosely coupledAspect Oriented Programming
(AOP) - separation of business logic from system servicesIoC container
- manages bean lifecycleMVC framework
for web applicationTransaction management
of DB, File operationsException 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
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 containerprototype
- many instances per IoC containerrequest
- one instance per HTTP request lifecyclesession
- one instance per HTTP session lifecycleglobal-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.
Bean Lifecycle
- Ioc Container instantiates beans from the bean definition configuration file.
- IoC populates properties
- Aware interfaces are called
- ifBeanNameAware
interface is implemented, then callssetBeanName()
- ifBeanFactoryAware
interface is implemented, then callssetBeanFactory()
- ifAppliactionContextAware
interface is implemented, then callssetApplicationContext()
- If
BeanPostProcessor
is associated with the bean, then their postProcessBeforeInitialization is called in order
-@PostConstruct
-afterPropertiesSet()
defined in InitializingBean
- custominit-method
definition - If
BeanPostProcessor
is associated with the bean, then theirpostProcessAfterInitialization
is called - Bean is ready
- If the
ApplicationContext
is closed, then the destroy methods are called in order
-@PreDestroy
-destroy()
defined in DisposableBean
- customdestroy-method
definition
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 beanbyType
- wires by class typeconstructor
- same as byType but applies to constructor argumentsautodetect
- constructor or byType
There are also some limitations
- Overriding possibility — by
property
andconstructor-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
- @Resource -
javax.annotation
The dependencies are resolved in the following order.
- ByName
- ByType
- ByQualifier (
@Qualifier
inorg.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
andexcludeFilters
include-filter
andexclude-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
XML-centric use of @Configuration
classes
@Configuration
class-centric use of XML with @ImportResource
References
BeanFactory
ApplicationContext
FileSystemXmlApplicationContext
ClassPathXmlApplicationContext
GenericApplicationContext
GenericGroovyApplicationContext
WebApplicationContext
XmlWebApplicationContext
AnnotationConfigApplicationContext
AnnotationConfigWebApplicationContext
@Configuration
@Bean
@Required
BeanFactoryPostProcessor
BeanPostProcessor