Spring Framework and Maven Overview
Spring Framework and Maven Overview
WEEK -7
Spring Framework
7.1 What is Apache Maven:
Maven is a powerful project management tool that is based on POM (project object model).
It is used for projects build, dependency and documentation.
In short terms we can tell maven is a tool that can be used for building and managing any
Java-based project.
Maven make the day-to-day work of Java developers easier and generally help with the
comprehension of any Java-based project
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link] [Link]
[Link]">
<modelVersion>4.0.0</modelVersion>
<groupId>[Link]</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>testng</artifactId>
<version>7.11.0</version>
<scope>test</scope>
</dependency>
<!-- [Link] -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>9.4.0</version>
</dependency>
</dependencies>
</project>
Spring improves coding efficiency and reduces overall application development time because
it is lightweight -- efficient at utilizing system resources -- and has a lot of support.
Spring removes tedious configuration work so that developers can focus on writing business
logic.
Spring handles the infrastructure so developers can focus on the application.
7.7 Benefits of Spring Framework:
Simplified Development: Spring reduces boilerplate code with features like Dependency
Injection and AOP, making development faster and easier.
Loose Coupling: Dependency Injection ensures components are loosely coupled, improving
maintainability and testability.
Modular: Spring's modular architecture allows developers to use only the required
components, improving flexibility and efficiency.
Integration Support: Spring provides built-in support for various technologies like JDBC,
JMS and JPA, making integration with other systems seamless.
Scalability: Spring's lightweight nature and support for various web and enterprise
components make it highly scalable for large applications.
1. Core Container:
This is the foundation of the framework and includes:
Core: Provides the fundamental IoC and DI functionalities, managing the lifecycle of
application components (beans).
Beans: Responsible for creating and managing Spring Beans, which are the objects forming
the backbone of a Spring application. It provides a sophisticated implementation of the factory
pattern, the BeanFactory.
Context: Built upon the Core and Beans modules, it provides the ApplicationContext
interface, offering access to objects defined within the configuration and extending the
BeanFactory with enterprise-specific features like message resources and event handling.
Spring Expression Language (SpEL): A powerful expression language for querying and
manipulating object graphs at runtime.
2. Data Access/Integration:
JDBC: Provides an abstraction layer over raw JDBC, simplifying database interactions.
ORM: Facilitates integration with Object-Relational Mapping (ORM) frameworks like
Hibernate, JPA, and JDO.
OXM: Offers abstraction over Java Object XML Marshalling (OXM) implementations like
JAXB and XStream.
JMS: Provides support for Java Message Service (JMS) for asynchronous messaging.
Transactions: Offers a consistent transaction management abstraction across various
transaction APIs.
3. Web:
Web-MVC: Implements the Model-View-Controller (MVC) design pattern for building web
applications.
Web-Socket: Provides support for WebSocket communication.
Web-Portlet: Supports building web portlets for portal environments.
4. Aspect –Oriented Programming, Instrumentation and Testing:
Aspect-Oriented Programming (AOP):
Enables the separation of cross-cutting concerns (e.g., logging, security) from business logic,
improving modularity.
Instrumentation:
Provides support for class instrumentation and classloader enhancements.
Testing:
Offers support for testing Spring applications with various testing frameworks.
Spring Boot Starters : It is one of the major key features or components of Spring
Boot Framework. The main responsibility of Spring Boot Starter is to combine a group
of common or related dependencies into single dependencies. When we add “spring-
boot-starter-web” jar file dependency to our build file, then Spring Boot Framework
will automatically download all required jars and add to our project classpath.
Spring Boot AutoConfigurator: Traditional Spring Framework requires lots of
configurations and for this it uses either
• XML Configuration or
• Annotation Configuration.
Spring Boot Starter reduces build’s dependencies and Spring Boot AutoConfigurator
reduces the Spring Configuration.
Spring Boot CLI Spring Boot CLI (Command Line Interface): It is Spring Boot
software to run and test Spring Boot applications from command prompt. When we
run Spring Boot applications using CLI, then it internally uses Spring Boot Starter and
Spring Boot AutoConfigurate components to resolve all dependencies and execute the
application.
Spring Boot Actuator: When we run our Spring Boot Web Application, Spring Boot
Actuator automatically provides hostname as “localhost” and default port number as
Spring Boot is a Java framework that makes it easier to create and run Java applications. It
simplifies the configuration and setup process, allowing developers to focus more on writing
code for their applications.
Spring Boot, a module of the Spring framework, facilitates Rapid Application Development
(RAD) capabilities.
Spring Boot is an open-source Java framework used to create a Micro Service.
it provides a faster way to set up and an easier, configure, and run both simple and web-based
applications.
It is a combination of Spring Framework and Embedded Servers. The main goal of Spring
Boot is to reduce development, unit test, and integration test time and in Spring Boot, there is
no requirement for XML configuration.
Spring Boot is a powerful and widely-used framework in the Java ecosystem, designed to simplify the
development of web and enterprise applications.
Rapid Development: Spring Boot enables Rapid Application Development (RAD) by
minimizing boilerplate code and configuration.
Auto-Configuration: It automatically configures your application based on the dependencies
you include, saving time and reducing errors.
Embedded Servers: You can run applications directly with embedded servers like Tomcat
or Jetty—no need for external deployment setups.
Spring Initializr is a Web-based tool that generates the Spring Boot project structure. The
spelling mistake in initializr is inspired by initializr.
It is very easy for the developers to select the necessary configuration for their projects.
The Spring Initializr tool takes care of the following configuration for any Spring-based
project.
Build tool(Maven or Gradle) to build the application.
Spring Boot version(Dependencies are added based on the version).
Dependencies required for the project.
Language and its version.
Project Metadata like name, packaging (Jar or War), package name etc.
The Spring Initializr UI has the following options,
Project: Using this one can create Maven or Gradle project i.e; Maven or Gradle can be used
as a build tool. The default option is Maven Project. Maven project is used in the entire
tutorial.
Language: Spring Initializr provide Java, Kotlin and Groovy as a programming language for
the project. Java is the default option.
Spring Boot Version: Using this one can select the Spring Boot version for their project.
Spring Boot latest Version is 2.5.0. The SNAPSHOT versions are under development and are
not stable.
Project Dependencies: Dependencies are artifacts that we can add to the project. I am
selecting Web Dependency.
Project Metadata: It is the information about the project.
Spring annotations are a form of metadata used in the Spring Framework to configure and
define the behavior of Spring-managed components.
They provide a declarative way to express intentions and guide the Spring container in
processing classes, methods, and fields during runtime.
This approach significantly simplifies configuration compared to older XML-based methods,
leading to cleaner, more readable, and easier-to-maintain code
Spring Annotation Description
@Entity Marks a class as a JPA entity (mapped to DB table)
@Id This annotation is the JPA is used for making specific variable
primary key.
@SpringBootApplication This annotation is used to mark the main class of a Spring Boot
application. It is a combination of three annotations
@EnableAutoConfiguration, @ComponentScan, and
@Configuration.
@Autowired Used for dependency injection (field, setter, or constructor).
@GetMapping It maps the HTTP GET requests on the specific handler method. It is
used to create a web service endpoint that fetches
@PostMapping It maps the HTTP POST requests on the specific handler method. It
is used to create a web service endpoint that creates
@PutMapping It maps the HTTP PUT requests on the specific handler method. It is
used to create a web service endpoint that creates or updates
@DeleteMapping It maps the HTTP DELETE requests on the specific handler method.
It is used to create a web service endpoint that deletes a resource.
@RestController It can be considered as a combination of @Controller and
@ResponseBody annotations
@RequestBody Binds JSON/XML request body to a Java object.
@ResponseBody Converts method return value into JSON/XML.
@Table Specifies table details for an entity.
@GeneratedValue Specifies primary key generation strategy.
@Column Maps an entity field to a DB column.
@Transactional Defines transaction boundaries.
@ComponentSca Automatically scans and registers beans from the package.
@Qualifier Specifies which bean to inject when multiple candidates exist.
@Primary Marks a bean as the default when multiple beans of the same type are
available.
[Link] = age;
}
//[Link]
public class StudentDetail {
private StudentData sdata;
public StudentDetail(StudentData sdata) {
super();
[Link] = sdata;
}
public void display() {
[Link]("=====Student Details====");
[Link]();
}
}
//[Link]
import [Link];
import [Link];
}
//[Link]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="
[Link]
[Link]
<bean id ="s" class ="StudentDetail">
<constructor-arg name="sdata" ref="sd" />
</bean>
</beans>
Example: Setter Injection
//[Link]
public class StudentData {
private String regno;
private String sname;
private int age;
[Link] = sname;
}
}
//[Link]
public class StudentDetail {
private StudentData sdata;
}
//[Link]
import [Link];
import [Link];
}
//[Link]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="
[Link]
[Link]
<bean id ="s" class ="StudentDetail">
<property name="sdata" ref="sd" />
</bean>
</beans>
Example: Field Injection
//[Link]
public class StudentData {
private String regno;
private String sname;
private int age;
public void setRegno(String regno) {
[Link] = regno;
}
//[Link]
import [Link];
public class StudentDetail {
@Autowired
private StudentData sdata;
public void display() {
[Link]("=====Student Details====");
[Link]();
}
}
//[Link]
import [Link];
import [Link];
}
//[Link]
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:context="[Link]
xsi:schemaLocation="[Link]
[Link]
[Link]
[Link] ">
<context:annotation-config />
</beans>
7.16 ApplicationContext:
The ApplicationContext represents the Spring IoC (Inversion of Control) container within the Spring
Framework. It is a central component responsible for instantiating, configuring, and assembling the
various objects (known as "beans") that constitute a Spring application.
Key Characteristics of ApplicationContext:
Spring IoC Container: The ApplicationContext is the primary interface for interacting with
the Spring IoC container. This container manages the lifecycle of application objects, from
creation to destruction, and handles their dependencies through Dependency Injection (DI).
Configuration Metadata: The ApplicationContext obtains its instructions for creating and
managing beans from configuration metadata. This metadata can be defined in various
formats, including XML, Java annotations, or Java code.
Implementation:
Implementation Description
ClassPathXmlApplicationContext Loads context from an XML file in the classpath
7.17 ComponentScan:
The @ComponentScan annotation tells Spring to scan specific packages for components
annotated with @Component, @Service, @Repository, or @Controller.
Without arguments, the @ComponentScan annotation scans the package of the annotated
class and its sub-packages by default.
The @ComponentScan annotation is used alongside @Configuration to define package
scanning in a configuration class.
The @ComponentScan annotation helps spring automatically detect and register beans
without needing manual bean declaration.
Example:
//[Link]
package ComponentAnnotation;
import [Link];
@Component
public class Student {
public void test() {
[Link]("Student name is Satish Patil");
}
}
//StudentConfig
package ComponentAnnotation;
import [Link];
import [Link];
@Configuration
@ComponentScan(basePackages = "ComponentAnnotation")
public class StudentConfig {
//[Link]
package ComponentAnnotation;
import [Link];
import [Link];
import [Link];
@Component
public class StudentName {
}
//[Link]
package [Link].StudentDemo1;
import [Link];
import [Link];
@Component
public class StudentDept {
@Autowired
StudentName sname;
public void studentdept() {
[Link]();
[Link]("Student Dept is EC");
}
}
//[Link]
package [Link].StudentDemo1;
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class StudentDemo1Application {
import [Link];
@Component
public class StudentName {
}
//[Link]
package [Link].StudentDemo1;
import [Link];
import [Link];
@Component
public class StudentDept {
StudentName sname;
//[Link]
package [Link].StudentDemo1;
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class StudentDemo1Application {
import [Link];
@Component
public class StudentName {
}
//[Link]
package [Link].StudentDemo1;
import [Link];
import [Link];
@Component
public class StudentDept {
StudentName sname;
@Autowired
public void setSname(StudentName sname) {
[Link] = sname;
}
public void studentdept() {
[Link]();
[Link]("Student Dept is EC");
}
//[Link]
package [Link].StudentDemo1;
import [Link];
import [Link];
import [Link];
@SpringBootApplication
public class StudentDemo1Application {
}
7.19 Autowiring:
Autowiring feature of spring framework enables us to inject the object dependency implicitly.
It internally uses setter or constructor injection.
Autowiring can't be used to inject primitive and string values. It works with reference only.
1. no: the default value – this means no autowiring is used for the bean and we have to explicitly
name the dependencies.
2. byName: autowiring is done based on the name of the property, therefore Spring will look for a
bean with the same name as the property that needs to be set.
3. byType: similar to the byName autowiring, only based on the type of the property. This means
Spring will look for a bean with the same type of the property to set. If there's more than one
bean of that type, the framework throws an exception.
4. constructor: autowiring is done based on constructor arguments, meaning Spring will look for
beans with the same type as the constructor arguments.
Example:
//[Link]
public class StudentName {
public void showname() {
[Link]("Student name is Satish Patil");
}
}
//[Link]
import [Link];
}
//[Link]
import [Link];
import [Link];
}
//[Link]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="
[Link]
[Link]
@Qualifier annotation is used with @Autowired to resolve ambiguity when multiple beans
of the same type are present in the Spring container.
It helps Spring determine which specific bean to inject by specifying the bean ID (name).
}
//[Link]
import [Link];
import [Link];
}
//[Link]
import [Link];
import [Link];
}
//[Link]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:context="[Link]
xsi:schemaLocation="[Link]
[Link]
[Link]
[Link] ">
<context:annotation-config />
<bean id="sd" class="StudentDetail">
</bean>
Bean Scopes refer to the lifecycle of a Bean, which means when the object of a Bean is instantiated,
how long it lives, and how many objects are created for that Bean throughout its lifetime. Basically, it
controls the instance creation of the bean, and it is managed by the Spring container.
The Spring framework provides five scopes for a bean. We can use three of them only in the context
of a web-aware Spring ApplicationContext, and the rest of the two are available for both an IoC
container and a Spring-MVC container. The following are the different scopes provided for a bean:
Session: Scopes a single bean definition to the lifecycle of an HTTP Session. But only valid
in the context of a web-aware Spring ApplicationContext.
Global-Session: Scopes a single bean definition to the lifecycle of a global HTTP Session. It
is also only valid in the context of a web-aware Spring ApplicationContext
Example:Singleton
//[Link]
public class Student {
private String name;
}
//[Link]
import [Link];
import [Link];
[Link]("s1 and s2 are both referring to the same object: " +(s == s1));
}
//[Link]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<bean id ="s" class="Student" scope="singleton" >
<property name="name" value="Satish Patil"></property>
</bean>
</beans>
Output:
Student name is Satish Patil
Student name is Satish Patil
s1 and s2 are both referring to the same object: true
Address of s1Student@318ba8c8
Address of s2Student@318ba8c8
Example:Prototype
//[Link]
public class Student {
private String name;
}
//[Link]
import [Link];
import [Link];
[Link]("s1 and s2 are both referring to the same object :" +(s == s1));
}
//[Link]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<bean id ="s" class="Student" scope="prototype" >
<property name="name" value="Satish Patil"></property>
</bean>
</beans>
Output:
Student name is Satish Patil
Student name is Satish Patil
s1 and s2 are both referring to the same object: false
Address of s1Student@33afa13b
Address of s2Student@7a4ccb53