Spring
Spring
Spring
IoC Container:
- Definition:
The Inversion of Control (IoC) Container in Spring is the core of the Spring
Framework, responsible for managing the lifecycle of beans (objects). It controls the
instantiation, configuration, and assembly of these beans, thus enabling loose
coupling between components.
- Functionality:
The IoC Container works by using configuration metadata, which could be in the form
of XML, annotations, or Java-based configuration, to understand how the objects
should be instantiated, wired, and managed.
- Types:
Spring provides two main types of IoC containers:
- BeanFactory:
A basic container with lazy initialization of beans.
-ApplicationContext:
A more advanced container that includes additional features such as event
propagation, declarative mechanisms to create a bean, and support for
internationalization.
Dependency Injection:
- Definition:
Dependency Injection (DI) is a design pattern used to implement IoC, where the
control of creating and managing the dependent objects (dependencies) is
transferred from the object itself to the IoC Container.
- Types of DI:
- Constructor Injection:
Dependencies are provided through a class constructor.
- Setter Injection:
Dependencies are provided through setter methods after the object is constructed.
-Field Injection:
(less commonly recommended): Dependencies are injected directly into fields
(attributes).
- Benefits:
DI promotes loose coupling between classes, improves code readability and
testability, and makes it easier to manage and maintain the application. It also allows
for easier switching between different implementations of a dependency.
Example:
// Constructor Injection
public Car(Engine engine) {
this.engine = engine;
}
// Setter Injection
public void setEngine(Engine engine) {
this.engine = engine;
}
In this example, the `Car` class depends on the `Engine` class. Instead of creating an
`Engine` object inside the `Car` class, the dependency is injected via the constructor
or setter method by the IoC Container.
The Spring Framework offers several advantages, making it one of the most popular
Java frameworks for enterprise application development. Here are the key benefits:
● IoC: The IoC principle allows developers to delegate the control of object
creation and dependency management to the Spring IoC Container, promoting
loose coupling between components.
● DI: Dependency Injection simplifies code, making it more maintainable,
testable, and modular. It also allows for easy swapping of different
implementations.
8. Security
● Large Community: Spring has a large and active community, which means
abundant resources, tutorials, and support are available.
● Extensive Ecosystem: The Spring ecosystem includes projects like Spring Boot,
Spring Cloud, and Spring Batch, which extend the capabilities of the core
framework and simplify the development of complex, distributed systems.
● Non-Intrusive: Spring allows you to use only the features you need, without
forcing you to adopt a specific programming model or platform.
● Portability: Spring applications can be easily deployed on various
environments, from standalone servers to cloud platforms, enhancing
portability and reducing vendor lock-in.
These advantages make Spring a preferred choice for developers building scalable,
maintainable, and enterprise-grade Java applications.
Explain Spring Framework with Architecture ?
The Spring framework consists of several modules, which can be categorized into
four main areas: Core Container, Data Access/Integration, Web, and
Miscellaneous. The Core Container provides the fundamental functionality of the
Spring framework, including the IoC container and ApplicationContext. The Data
Access/Integration area provides support for integrating with databases and other
data sources. The Web area provides support for building web applications,
including the Spring MVC and Spring WebFlux modules. The Miscellaneous area
includes other modules that provide additional functionality, such as the Spring
Security module for authentication and authorization features.
● After setting up, your project directory will have the following structure:
helloworld/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/helloworld/
│ │ │ ├── HelloWorldApplication.java
│ │ │ └── HelloWorldController.java
│ │ └── resources/
│ │ └── application.properties
└── pom.xml
3.Create the Main Application Class
package com.example.helloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
SpringApplication.run(HelloWorldApplication.class, args);
4.Create a Controller
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@GetMapping("/hello")
● You can run the application using your IDE or the command line.
● Command Line: Navigate to the project directory and execute:
mvn spring-boot:run
Annotations in Spring play a crucial role in simplifying configuration and development. They help
eliminate the need for verbose XML configurations by allowing you to define metadata directly in
your code. Here’s an overview of some of the most important annotations in Spring:
1. @SpringBootApplication
● Purpose: Marks the main class of a Spring Boot application and triggers auto-configuration,
component scanning, and allows defining extra configuration on your application class.
● Usage: This annotation combines three key annotations: @Configuration,
@EnableAutoConfiguration, and @ComponentScan.
java
Copy code
@SpringBootApplication
SpringApplication.run(MyApplication.class, args);
● Purpose: These annotations are used to define Spring beans and indicate the role of the class
in the application. Spring automatically detects these classes through component scanning
and registers them as beans.
// Bean logic
●
@Service: Specialization of @Component, used for service layer classes.
java
Copy code
@Service
// Business logic
@Repository: Specialization of @Component, used for DAO (Data Access Object) classes.
java
Copy code
@Repository
3. @Autowired
java
Copy code
@Service
this.myRepository = myRepository;
4. @Qualifier
● Purpose: Used along with @Autowired to specify which bean to inject when multiple
beans of the same type are available.
● Usage: Provides the name of the specific bean to be injected.
java
Copy code
@Autowired
@Qualifier("specificBeanName")
5. @Configuration
● Purpose: Indicates that a class contains @Bean definitions and Spring should process it to
generate Spring beans to be managed by the Spring IoC container.
● Usage: Often used in place of XML configuration files.
java
Copy code
@Configuration
@Bean
}
6. @Bean
● Purpose: Declares a method as a bean producer, and the returned object is registered as a
Spring bean.
● Usage: Typically used within a class annotated with @Configuration.
java
Copy code
@Bean
7. @Scope
java
Copy code
@Bean
@Scope("prototype")
8. @Primary
● Purpose: Indicates that a bean should be given preference when multiple beans of the same
type are eligible for autowiring.
● Usage: Applied on a bean definition.
java
Copy code
@Bean
@Primary
9. @Value
● Purpose: Injects values into fields, constructor arguments, or method parameters from a
property file or environment variables.
● Usage: Used for injecting configuration values.
java
Copy code
@Value("${my.property}")
● @Controller: Marks a class as a Spring MVC controller, which can handle web requests.
● @RestController: A combination of @Controller and @ResponseBody, used to create
RESTful web services.
● @RequestMapping: Maps HTTP requests to handler methods in MVC and REST controllers.
java
Copy code
@RestController
@RequestMapping("/api")
@GetMapping("/hello")
}
11. @RequestParam, @PathVariable, @RequestBody
java
Copy code
@GetMapping("/greet")
●
● @PathVariable: Binds URI template variables to method parameters.
○ Example: If the request URL is http://example.com/api/users/1, the
value 1 can be accessed using @PathVariable.
java
Copy code
@GetMapping("/users/{id}")
●
● @RequestBody: Binds the body of an HTTP request to a method parameter. Typically used to
pass JSON or XML data in POST requests.
○ Example: For a POST request with a JSON body, the data can be mapped to a Java
object using @RequestBody.
java
Copy code
@PostMapping("/users")
return user;
}
12. @ResponseBody
● Purpose: Indicates that the return value of a method should be used as the response body of
the HTTP response, rather than being interpreted as a view name.
● Usage: Commonly used in RESTful web services to return data directly, such as JSON or XML.
@GetMapping("/data")
@ResponseBody
13. @CrossOrigin
● Purpose: Enables cross-origin resource sharing (CORS) for a controller or a specific method.
This is important when your backend and frontend are on different domains or ports.
● Usage: Applied at the class or method level.
@RestController
@CrossOrigin(origins = "http://example.com")
@GetMapping("/data")
14. @Transactional
@Transactional
// Transactional logic
15. @EnableAutoConfiguration
● Purpose: Automatically configures Spring Boot based on the dependencies you have added
to your project. This annotation is typically included in @SpringBootApplication.
● Usage: Enables auto-configuration in a Spring Boot application.
@EnableAutoConfiguration
SpringApplication.run(MyApplication.class, args);
}
Explain Spring Bean Life Cycle Process Flow ?
The lifecycle of any object means when & how it is born, how it behaves
throughout its life, and when & how it dies. Similarly, the bean life cycle
refers to when & how the bean is instantiated, what action it performs
until it lives, and when & how it is destroyed. In this article, we will discuss
the life cycle of the bean.
Bean life cycle is managed by the spring container. When we run the
program then, first of all, the spring container gets started. After that, the
container creates the instance of a bean as per the request, and then
dependencies are injected. And finally, the bean is destroyed when the
spring container is closed. Therefore, if we want to execute some code on
the bean instantiation and just after closing the spring container, then we
can write that code inside the custom init() method and the destroy()
method.
The following image shows the process flow of the bean life cycle.
2. Update pom.xml
xml
Copy code
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
<properties>
<spring.mvc.view.suffix>.jsp</spring.mvc.view.suffix>
</properties>
In src/main/resources/application.properties:
properties
Copy code
# MySQL Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/spring_jdbc
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JDBC
spring.datasource.initialize=true
java
Copy code
package com.example.springjdbc.dao;
import com.example.springjdbc.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
});
@Override
});
Create a normal Spring MVC controller that handles HTTP requests and returns views (JSP pages).
java
Copy code
package com.example.springjdbc.controller;
import com.example.springjdbc.dao.StudentDAO;
import com.example.springjdbc.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/students")
@Autowired
@GetMapping
model.addAttribute("students", students);
@GetMapping("/{id}")
model.addAttribute("student", student);
return "student"; // Corresponds to student.jsp
@GetMapping("/new")
@PostMapping
studentDAO.save(student);
return "redirect:/students";
@GetMapping("/edit/{id}")
model.addAttribute("student", student);
@PostMapping("/{id}")
studentDAO.update(student);
return "redirect:/students";
@GetMapping("/delete/{id}")
studentDAO.delete(id);
return "redirect:/students";
students.jsp
jsp
Copy code
<html>
<head>
<title>Students</title>
</head>
<body>
<h2>Students List</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Course</th>
<th>Actions</th>
</tr>
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.course}</td>
<td>
<a href="students/edit/${student.id}">Edit</a>
<a
href="students/delete/${student.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
student.jsp
jsp
Copy code
<html>
<head>
<title>Student Details</title>
</head>
<body>
<h2>Student Details</h2>
<p>ID: ${student.id}</p>
<p>Name: ${student.name}</p>
<p>Course: ${student.course}</p>
</body>
</html>
create-student.jsp
jsp
Copy code
<html>
<head>
<title>Create Student</title>
</head>
<body>
<h2>Create Student</h2>
</form>
</body>
</html>
edit-student.jsp
jsp
Copy code
<html>
<head>
<title>Edit Student</title>
</head>
<body>
<h2>Edit Student</h2>
</form>
</body>
</html>
8. Create the Database Table
sql
Copy code
name VARCHAR(100),
course VARCHAR(100)
);
Summary
This example demonstrates how to use Spring JDBC with JSP and a normal Spring MVC controller to
perform CRUD operations with a MySQL database. This approach uses JSP for the view layer and
follows the traditional Model-View-Controller (MVC) pattern in Spring.
Set Up the Spring Boot Project
2. Update pom.xml
xml
Copy code
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
<properties>
<spring.mvc.view.suffix>.jsp</spring.mvc.view.suffix>
</properties>
In src/main/resources/application.properties:
properties
Copy code
# MySQL Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/spring_jdbc
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JDBC
spring.datasource.initialize=true
java
Copy code
package com.example.springjdbc.dao;
import com.example.springjdbc.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
@Autowired
@Override
});
}
public List<Student> findAll() {
@Override
});
Create a normal Spring MVC controller that handles HTTP requests and returns views (JSP pages).
java
Copy code
package com.example.springjdbc.controller;
import com.example.springjdbc.dao.StudentDAO;
import com.example.springjdbc.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/students")
@Autowired
@GetMapping
model.addAttribute("students", students);
@GetMapping("/{id}")
model.addAttribute("student", student);
@GetMapping("/new")
public String showCreateForm(Model model) {
@PostMapping
studentDAO.save(student);
return "redirect:/students";
@GetMapping("/edit/{id}")
model.addAttribute("student", student);
@PostMapping("/{id}")
student.setId(id);
studentDAO.update(student);
return "redirect:/students";
}
@GetMapping("/delete/{id}")
studentDAO.delete(id);
return "redirect:/students";
students.jsp
jsp
Copy code
<html>
<head>
<title>Students</title>
</head>
<body>
<h2>Students List</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Course</th>
<th>Actions</th>
</tr>
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.course}</td>
<td>
<a href="students/edit/${student.id}">Edit</a>
<a
href="students/delete/${student.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
student.jsp
jsp
Copy code
<html>
<head>
<title>Student Details</title>
</head>
<body>
<h2>Student Details</h2>
<p>ID: ${student.id}</p>
<p>Name: ${student.name}</p>
<p>Course: ${student.course}</p>
</body>
</html>
create-student.jsp
jsp
Copy code
<html>
<head>
<title>Create Student</title>
</head>
<body>
<h2>Create Student</h2>
</form>
</body>
</html>
edit-student.jsp
jsp
Copy code
<html>
<head>
<title>Edit Student</title>
</head>
<body>
<h2>Edit Student</h2>
</form>
</body>
</html>
sql
Copy code
CREATE TABLE students (
name VARCHAR(100),
course VARCHAR(100)
);
Summary
This example demonstrates how to use Spring JDBC with JSP and a normal Spring MVC controller to
perform CRUD operations with a MySQL database. This approach uses JSP for the view layer and
follows the traditional Model-View-Controller (MVC) pattern in Spring.
To demonstrate the use of Spring Boot with CrudRepository, JSP for views, and MySQL for the
database, we'll create a simple application to manage Employee entities. This application will
perform basic CRUD operations: Create, Read, Update, and Delete.
2. Update pom.xml
xml
Copy code
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
<properties>
<spring.mvc.view.prefix>/WEB-INF/jsp/</spring.mvc.view.prefix>
<spring.mvc.view.suffix>.jsp</spring.mvc.view.suffix>
</properties>
properties
Copy code
# MySQL Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/crud_example
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA Hibernate
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
java
Copy code
package com.example.crudrepojsp.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Employee() {}
this.name = name;
this.department = department;
this.email = email;
return id;
this.id = id;
return name;
}
public void setName(String name) {
this.name = name;
return department;
this.department = department;
return email;
this.email = email;
@Override
}
5. Create the EmployeeRepository Interface
java
Copy code
package com.example.crudrepojsp.repository;
import com.example.crudrepojsp.model.Employee;
import org.springframework.data.repository.CrudRepository;
Create a Spring MVC controller to handle requests and return JSP views.
java
Copy code
package com.example.crudrepojsp.controller;
import com.example.crudrepojsp.model.Employee;
import com.example.crudrepojsp.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/employees")
@Autowired
@GetMapping
model.addAttribute("employees",
employeeRepository.findAll());
@GetMapping("/new")
@PostMapping
employeeRepository.save(employee);
return "redirect:/employees";
}
@GetMapping("/edit/{id}")
Employee employee =
employeeRepository.findById(id).orElseThrow(() -> new
IllegalArgumentException("Invalid employee Id:" + id));
model.addAttribute("employee", employee);
@PostMapping("/{id}")
employee.setId(id);
employeeRepository.save(employee);
return "redirect:/employees";
@GetMapping("/delete/{id}")
Employee employee =
employeeRepository.findById(id).orElseThrow(() -> new
IllegalArgumentException("Invalid employee Id:" + id));
employeeRepository.delete(employee);
return "redirect:/employees";
}
}
employees.jsp
jsp
Copy code
<html>
<head>
<title>Employees</title>
</head>
<body>
<h2>Employees List</h2>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Department</th>
<th>Email</th>
<th>Actions</th>
</tr>
<tr>
<td>${employee.id}</td>
<td>${employee.name}</td>
<td>${employee.department}</td>
<td>${employee.email}</td>
<td>
<a href="employees/edit/${employee.id}">Edit</a>
<a
href="employees/delete/${employee.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
create-employee.jsp
jsp
Copy code
<html>
<head>
<title>Create Employee</title>
</head>
<body>
<h2>Create Employee</h2>
</form>
</body>
</html>
edit-employee.jsp
jsp
Copy code
<html>
<head>
<title>Edit Employee</title>
</head>
<body>
<h2>Edit Employee</h2>
</form>
</html>
sql
Copy code
USE crud_example;
name VARCHAR(100),
department VARCHAR(100),
email VARCHAR(100)
);