0% found this document useful (0 votes)
5 views

Spring Core Session 1

The Spring Framework is a comprehensive Java platform that provides infrastructure support for developing applications, focusing on features like dependency injection, transaction management, and security. It consists of various modules, including Spring Core, Spring MVC, Spring Security, and Spring Boot, each offering specific functionalities to enhance application development. The framework promotes modular, maintainable, and scalable applications by managing object creation and configuration through its IoC container, allowing developers to concentrate on business logic rather than infrastructure concerns.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Spring Core Session 1

The Spring Framework is a comprehensive Java platform that provides infrastructure support for developing applications, focusing on features like dependency injection, transaction management, and security. It consists of various modules, including Spring Core, Spring MVC, Spring Security, and Spring Boot, each offering specific functionalities to enhance application development. The framework promotes modular, maintainable, and scalable applications by managing object creation and configuration through its IoC container, allowing developers to concentrate on business logic rather than infrastructure concerns.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

The Spring Framework is a Java platform that provides comprehensive infrastructure support for

developing Java applications. Spring handles the infrastructure so you can focus on your
application.

Form data collection , Validation and binding the values with the object
Security
Transaction Management
Objects & Memory management
Logging
Testing
Exception Handling
Integrating with other systems

Some of the benefits of the framework:

● Make a Java method execute in a database transaction without having to deal with
transaction APIs.
● Make a local Java method an HTTP endpoint without having to deal with the Servlet API.
● Make a local Java method a message handler without having to deal with the JMS API
● The Spring Framework codifies formalized design patterns (Factory, Abstract Factory,
Builder, Decorator, Service Locator etc) as first-class objects that you can integrate into
your own application(s). Hence we can build robust, maintainable applications.

Framework Modules:
The Spring Framework consists of various modules that provide different functionalities and
features. Here are some of the key modules of the Spring Framework eco system:
Spring Core: This module provides the fundamental features of the Spring Framework,
including Dependency Injection (DI) and Inversion of Control (IoC) container. It serves as
the foundation for other modules.
Spring MVC: The Spring MVC (Model-View-Controller) module provides a web framework
for building web applications. It follows the MVC pattern, allowing developers to separate
the concerns of handling requests, processing data, and rendering views.
Spring Data: The Spring Data module simplifies data access and provides a consistent
approach to working with databases. It offers integration with various data storage
technologies, including relational databases, NoSQL databases, and more.
Spring Security: This module provides security features and authentication and
authorization mechanisms for Spring applications. It helps protect against common
security vulnerabilities and offers a wide range of features for securing web applications.
Spring Boot: Spring Boot is not just a module but a separate project within the Spring
ecosystem. It simplifies the process of creating stand-alone, production-grade Spring
applications. It offers auto-configuration, embedded servers, opinionated defaults, and a
seamless development experience.
Spring Integration: The Spring Integration module provides support for building enterprise
integration solutions. It enables communication and interaction between different
systems and applications using messaging, EIP (Enterprise Integration Patterns), and
adapters.
Spring Batch: This module offers support for batch processing and batch jobs in Spring
applications. It provides features for reading, processing, and writing large amounts of
data efficiently.
Spring AOP: The Spring AOP (Aspect-Oriented Programming) module provides support for
Aspect-Oriented Programming. It enables developers to modularize cross-cutting
concerns, such as logging, security, and transaction management, into separate
aspects.
Spring Test: The Spring Test module provides testing support for Spring applications. It
offers utilities and annotations for writing unit tests, integration tests, and end-to-end
tests for Spring components.
Spring Cloud: Spring Cloud is a collection of modules that helps in building distributed
systems and microservices architectures. It provides features such as service discovery,
configuration management, circuit breakers, and distributed tracing.

The Spring Core module forms the foundational building block of the Spring Framework,
providing the essential infrastructure for developing enterprise-grade Java applications. It
focuses on managing and configuring application components, facilitating dependency injection,
and enabling loose coupling between various application modules.
Key features of the Spring Core module include:

Dependency Injection (DI): Spring Core introduces a powerful inversion of control (IoC)
container that manages the lifecycle of application objects and their dependencies. DI
allows you to define and inject dependencies between classes, promoting modularity
and testability.
Bean Management: The IoC container, also known as the Spring container, manages
beans (application components) by creating and managing their instances, controlling
their scope, and handling their lifecycle events.
Bean Configuration: Spring Core supports multiple ways of configuring beans, including
XML-based configuration, Java annotations, and Java-based configuration classes. This
flexibility allows developers to choose the most suitable approach for their application.
Resource Access: Spring Core offers streamlined access to resources such as files,
databases, URLs, and more, through its resource abstraction layer. This simplifies
resource handling and enhances portability.
Internationalization (i18n): The module includes comprehensive support for
internationalization and localization, allowing applications to display messages in
different languages and adapt to various regions.
Event Handling: Spring's event publishing mechanism enables communication between
different parts of an application through events and listeners, facilitating a decoupled
communication model.
Validation: Spring Core provides validation support for input data using a flexible validation
framework that integrates seamlessly with Spring applications.
AOP (Aspect-Oriented Programming): While AOP is more extensively covered in the
Spring AOP module, Spring Core introduces basic support for aspect-oriented
programming, allowing the separation of cross-cutting concerns from the application's
core logic.

In essence, the Spring Core module lays the foundation for the entire Spring Framework,
fostering modular, maintainable, and scalable applications through its dependency management
and IoC features. It promotes the use of design patterns and best practices, enabling
developers to focus on business logic rather than intricate infrastructure concerns.

IoC is also known as dependency injection (DI). It is a process whereby objects define their
dependencies, that is, the other objects they work with, only through constructor arguments,
arguments to a factory method, or properties that are set on the object instance after it is
constructed or returned from a factory method. The container then injects those dependencies
when it creates the bean. This process is fundamentally the inverse, hence the name Inversion
of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by
using direct construction of classes, or a mechanism such as the Service Locator pattern.

In the Spring Framework, the IOC (Inversion of Control) container is a fundamental component
that manages the creation, configuration, and life cycle of objects, also known as beans. The
IOC container is responsible for implementing the principle of dependency injection, which
promotes loose coupling and modular design in your application.
Here are some key aspects of the IOC container in Spring:
Dependency Injection (DI): The IOC container performs dependency injection, where
it resolves and injects dependencies into objects. Instead of objects creating their
dependencies, the IOC container creates and wires the dependencies for the objects,
reducing the need for explicit object creation and management.
Bean Configuration: The IOC container allows you to define the configuration of beans.
Bean configuration can be done using XML-based configuration files, Java-based
configuration classes, or a combination of both. The configuration specifies the
dependencies, properties, and behaviors of the beans.
Bean Lifecycle Management: The IOC container manages the lifecycle of beans,
including their creation, initialization, and destruction. It provides hooks and callbacks
for performing custom initialization and destruction logic, such as implementing the
InitializingBean and DisposableBean interfaces, or using annotations like
@PostConstruct and @PreDestroy.
Bean Scopes: Spring supports different bean scopes, such as singleton, prototype,
request, session, etc. The IOC container can create beans in different scopes to
control their lifecycle and visibility. For example, singleton scope creates a single
instance of a bean, while prototype scope creates a new instance each time the bean
is requested.
Autowiring: The IOC container can automatically wire dependencies by analyzing the
relationships between beans and their dependencies. Autowiring eliminates the need
for explicit dependency wiring in the configuration, reducing boilerplate code and
configuration effort.
Aspect-Oriented Programming (AOP): The IOC container integrates with AOP to
provide cross-cutting functionalities, such as logging, transaction management,
security, and caching. AOP allows you to modularize such cross-cutting concerns and
apply them to multiple beans in a declarative manner.
Container Hierarchy: Spring supports a container hierarchy where child containers
inherit configurations from their parent containers. This allows for modular and
scalable application design, with each container managing its own set of beans and
configurations.

The org.springframework.beans and org.springframework.context packages are the basis for


Spring Framework’s IoC container

BeanFactory
ApplicationContext

In Spring, the objects that form the backbone of your application and that are managed by the
Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and
otherwise managed by a Spring IoC container.

The interface org.springframework.context.ApplicationContext represents the Spring IoC


container and is responsible for instantiating, configuring, and assembling the aforementioned
beans. The container gets its instructions on what objects to instantiate, configure, and

assemble by reading configuration metadata.The configuration metadata is represented in XML,


Java annotations, or Java code.

The Spring IoC container consumes a form of configuration metadata; this configuration
metadata represents how you as an application developer tell the Spring container to
instantiate, configure, and assemble the objects in your application.
Configuration metadata can be supplied in three forms:

● XML based configuration


● Annotation-based configuration
● Java-based configuration

Spring configuration consists of one or more bean definitions that the container must manage

The following example shows the basic structure of XML-based configuration metadata:

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here →
</beans>
id: The id attribute is a string that we use to uniquely identify the bean with in the container
class: The class attribute represent the fully qualified class name of the bean

Instantiating a container:

Instantiating a Spring IoC container is straightforward. The location path or paths supplied
to an ApplicationContext constructor are actually resource strings that allow the container to
load configuration metadata from a variety of external resources such as the local file
system, from the Java CLASSPATH, and so on.

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml",


"daos.xml");

Here are the commonly used attributes:


id: Specifies a unique identifier for the bean within the container. It is used to reference the
bean in other parts of the configuration.
class: Specifies the fully qualified class name of the bean. It indicates the type of the bean
to be instantiated.
XML Based Configuration Examples:

Create a new project in intellij as shown in below screen:


Enter the name of the project and choose the Archetype as shown in the below screen:
By default it will use jdk 1.5 for compilation, change the jdk compiler reference to 17 as shown in
below screen, Go to the project settings to change the compiler options
Choose the values/options as shown below:
Then choose the project structure, to set the module settings
Change the language level settings from 1.5 to 17 as shown in the below screen:
Create a package (eg: com.raghtech.entities) as shown in the below screen:

Enter the package name as shown below:

Create a resources folder as shown below:


Enter the name of the directory as “resources”

Create a file under resources with name “entities.xml”

Enter the name as entities.xml


Update the pom.xml file i.e add the spring-beans and spring-context dependencies as shown
below:

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>SpringIOC</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>SpringIOC</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>6.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.2</version>
</dependency>
</dependencies>
</project>

Select the pom.xml and right click, from the options choose maven->reload project as shown in
the below screen: This action will load the required spring dependency jars from maven central
repository into the project external libraries path:
Create a new Java bean class under the com.raghtech.entities package:
Open Account.java file and type the below code

package com.raghtech.entities;

public class Account {


private int accNo;
private String holderName;
private int balance;

public Account() {
accNo=111;
holderName="John";
balance = 5000;
}

public int getAccNo() {


return accNo;
}

public void setAccNo(int accNo) {


this.accNo = accNo;
}

public String getHolderName() {


return holderName;
}

public void setHolderName(String holderName) {


this.holderName = holderName;
}

public int getBalance() {


return balance;
}

public void setBalance(int balance) {


this.balance = balance;
}
}

Open the entities.xml file and make the below entries in the file:

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="account" class="com.raghtech.entities.Account"/>

</beans>

Open App.java and modify the main method as shown below:

package org.example;

import com.raghtech.entities.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App


{
public static void main( String[] args )
{
ApplicationContext context = new
ClassPathXmlApplicationContext("entities.xml");
Account account = (Account) context.getBean("account");
String holderName = account.getHolderName();
System.out.println("Account Holder Name: "+holderName);
}
}

Build the project


Run the application as shown below:

You can see the Account Holder Name will be printed on the console.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy