0% found this document useful (0 votes)
7 views40 pages

Oop With Java - Unit 5

The document provides an overview of the Spring Framework, highlighting key concepts such as Inversion of Control (IoC), Dependency Injection (DI), Aspect-Oriented Programming (AOP), Spring MVC, Spring Boot, and Spring Data JPA. It explains how Spring manages object creation and dependencies, promotes loose coupling, and offers various configuration options. Additionally, it discusses the advantages of using Spring DI and IoC for building robust, maintainable, and scalable Java applications.

Uploaded by

mohdasad1528
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views40 pages

Oop With Java - Unit 5

The document provides an overview of the Spring Framework, highlighting key concepts such as Inversion of Control (IoC), Dependency Injection (DI), Aspect-Oriented Programming (AOP), Spring MVC, Spring Boot, and Spring Data JPA. It explains how Spring manages object creation and dependencies, promotes loose coupling, and offers various configuration options. Additionally, it discusses the advantages of using Spring DI and IoC for building robust, maintainable, and scalable Java applications.

Uploaded by

mohdasad1528
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OOP with JAVA

Unit -V Spring Framework

Spring Framework
The Spring Framework is a powerful and versatile framework for building Java applications. It provides a
comprehensive infrastructure for developing robust, maintainable, and scalable applications. Below is an
overview of key concepts in Spring, along with examples.

1. Inversion of Control (IoC) and Dependency Injection (DI)

• IoC: Spring manages the objects and their dependencies instead of the application code directly
handling object creation.
• DI: Spring injects the required dependencies into an object at runtime.

Example:

// Service class
public class UserService {
private UserRepository userRepository;

// Constructor-based Dependency Injection


public UserService(UserRepository userRepository) {
[Link] = userRepository;
}

public void registerUser(String username) {


[Link](new User(username));
}
}

// Repository interface
public interface UserRepository {
void save(User user);
}

// Configuration class
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserService(userRepository());
}

@Bean
public UserRepository userRepository() {
return new InMemoryUserRepository();
}
}

// Main class
public class Main {
public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext([Link]);
UserService userService = [Link]([Link]);
[Link]("Amaan");
}
}

2. Aspect-Oriented Programming (AOP)

• AOP: Allows you to separate cross-cutting concerns like logging, security, or transaction management
from the business logic.

Example:

@Aspect
public class LoggingAspect {
@Before("execution(* [Link](..))")
public void logBeforeRegister(JoinPoint joinPoint) {
[Link]("Logging before registering user: " +
[Link]().getName());
}
}

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
@Bean
public LoggingAspect loggingAspect() {
return new LoggingAspect();
}

@Bean
public UserService userService() {
return new UserService(userRepository());
}

@Bean
public UserRepository userRepository() {
return new InMemoryUserRepository();
}
}

3. Spring MVC

• Spring MVC: A model-view-controller framework for building web applications.

Example:

@Controller
public class HomeController {
@GetMapping("/home")
public String home(Model model) {
[Link]("message", "Welcome to Amaan's homepage!");
return "home";
}
}

@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
[Link]([Link], args);
}
}

4. Spring Boot

• Spring Boot: Simplifies the creation of production-ready applications by providing pre-configured


templates and dependencies.

Example:

@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
[Link]([Link], args);
}
}

@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Amaan!";
}
}

5. Spring Data JPA

• Spring Data JPA: Simplifies database access by providing a repository abstraction over JPA.

Example:

@Entity
public class User {
@Id
@GeneratedValue(strategy = [Link])
private Long id;
private String username;

// Getters and Setters


}

public interface UserRepository extends JpaRepository<User, Long> {


}

@Service
public class UserService {
@Autowired
private UserRepository userRepository;

public void registerUser(String username) {


[Link](new User(username));
}
}

@RestController
public class UserController {
@Autowired
private UserService userService;

@PostMapping("/register")
public void registerUser(@RequestParam String username) {
[Link](username);
}
}
Spring Core Basics-Spring Dependency Injection
Spring Core Basics: Spring Dependency Injection (DI)

Spring Core is the foundation of the Spring Framework, and one of its primary features is Dependency
Injection (DI). DI is a design pattern that removes the responsibility of object creation and management from
the application code, making it the responsibility of the Spring container.

Key Concepts of Dependency Injection

1. Inversion of Control (IoC):


o IoC: The Spring container manages the lifecycle and dependencies of objects (beans) instead of
the application code doing it directly.
2. Types of Dependency Injection:
o Constructor Injection: Dependencies are provided through a class constructor.
o Setter Injection: Dependencies are provided through setter methods.
o Field Injection: Dependencies are injected directly into class fields (less preferred due to
testability issues).
3. Spring Beans:
o Beans: Objects managed by the Spring container. They are instantiated, assembled, and managed
by the Spring IoC container.
4. Bean Configuration:
o XML Configuration: Beans are defined in an XML file.
o Java-based Configuration: Beans are defined using @Configuration and @Bean annotations.
o Annotation-based Configuration: Beans are defined using annotations like @Component,
@Service, @Repository, and @Controller.

Constructor Injection Example


// Service class
public class UserService {
private final UserRepository userRepository;

// Constructor-based Dependency Injection


public UserService(UserRepository userRepository) {
[Link] = userRepository;
}

public void registerUser(String username) {


[Link](new User(username));
}
}

// Repository interface
public interface UserRepository {
void save(User user);
}

// Configuration class using Java-based Configuration


@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserService(userRepository());
}

@Bean
public UserRepository userRepository() {
return new InMemoryUserRepository();
}
}

// Main class
public class Main {
public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext([Link]);
UserService userService = [Link]([Link]);
[Link]("Amaan");
}
}

Setter Injection Example


// Service class
public class UserService {
private UserRepository userRepository;

// Setter-based Dependency Injection


public void setUserRepository(UserRepository userRepository) {
[Link] = userRepository;
}

public void registerUser(String username) {


[Link](new User(username));
}
}

// Configuration class using Java-based Configuration


@Configuration
public class AppConfig {
@Bean
public UserService userService() {
UserService userService = new UserService();
[Link](userRepository());
return userService;
}

@Bean
public UserRepository userRepository() {
return new InMemoryUserRepository();
}
}

Annotation-based Configuration Example


// User class
@Component
public class UserService {
private final UserRepository userRepository;

@Autowired // This annotation enables automatic dependency injection


public UserService(UserRepository userRepository) {
[Link] = userRepository;
}

public void registerUser(String username) {


[Link](new User(username));
}
}

// Repository interface
@Repository
public interface UserRepository {
void save(User user);
}

// In-memory implementation of UserRepository


@Component
public class InMemoryUserRepository implements UserRepository {
@Override
public void save(User user) {
[Link]("User saved: " + [Link]());
}
}

// Configuration class
@Configuration
@ComponentScan(basePackages = "[Link]")
public class AppConfig {
}

// Main class
public class Main {
public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext([Link]);
UserService userService = [Link]([Link]);
[Link]("Amaan");
}
}

Key Points and Features

1. Loose Coupling:
o By injecting dependencies, classes are less dependent on each other, promoting loose coupling
and easier testing.
2. Configuration Flexibility:
o Spring allows beans to be configured using XML, annotations, or Java-based configuration.
3. Automatic Wiring:
o Spring can automatically inject dependencies using the @Autowired annotation, reducing the
need for manual configuration.
4. Bean Scopes:
o Spring supports different bean scopes (singleton, prototype, request, session, etc.), which
define the lifecycle of a bean.
5. Bean Lifecycle Management:
o Spring manages the complete lifecycle of beans, including initialization and destruction
callbacks (@PostConstruct, @PreDestroy).
6. Dependency Resolution:
o Spring resolves dependencies at runtime, ensuring that the required dependencies are available
before the bean is used.
Advantages of Using Spring DI:

• Testability: DI makes unit testing easier by allowing dependencies to be easily mocked or stubbed.
• Maintainability: Loose coupling and clear separation of concerns improve the maintainability of the
code.
• Flexibility: Spring's various configuration options provide flexibility in how applications are wired
together.

Conclusion

Spring Dependency Injection is a core concept that enables the development of loosely coupled, maintainable,
and testable applications. By understanding and utilizing DI, you can leverage the full power of the Spring
Framework to create scalable and robust Java applications.

Spring Inversion of Control


Spring Inversion of Control (IoC)

Inversion of Control (IoC) is a core principle of the Spring Framework. It refers to the design pattern where
the control of object creation, configuration, and management is transferred from the application to the
framework. In Spring, IoC is implemented through the Spring IoC Container, which is responsible for
managing the lifecycle and dependencies of the objects (beans) in the application.

Key Concepts of Inversion of Control

1. IoC Container:
o The IoC container in Spring is responsible for instantiating, configuring, and assembling the
beans. The container takes care of wiring dependencies, managing the lifecycle, and providing
beans to the application when needed.
2. Beans:
o In Spring, a bean is an object that is managed by the IoC container. Beans are typically
components of your application like services, repositories, controllers, etc.
3. Bean Configuration:
o Beans can be configured in Spring using XML, annotations, or Java-based configuration.
4. Dependency Injection (DI):
o IoC works closely with Dependency Injection, where dependencies (other beans) are injected
into a bean either via constructor, setter, or field injection.

Types of IoC Containers

1. BeanFactory:
o The simplest container in Spring. It provides basic IoC support and is primarily used for
lightweight, simple applications.
2. ApplicationContext:
o A more advanced container that builds on BeanFactory. It adds more enterprise-specific
functionalities like event propagation, declarative mechanisms to create a bean, etc.

Example of Inversion of Control with Java-Based Configuration

Step 1: Define a Service and Repository


// User class
public class User {
private String username;

public User(String username) {


[Link] = username;
}

public String getUsername() {


return username;
}
}

// UserRepository interface
public interface UserRepository {
void save(User user);
}

// InMemoryUserRepository implementation
public class InMemoryUserRepository implements UserRepository {
@Override
public void save(User user) {
[Link]("User " + [Link]() + " saved in memory.");
}
}

// UserService class
public class UserService {
private UserRepository userRepository;

// Constructor-based Dependency Injection


public UserService(UserRepository userRepository) {
[Link] = userRepository;
}

public void registerUser(String username) {


[Link](new User(username));
}
}

Step 2: Configure Beans with Java-Based Configuration

import [Link];
import [Link];

@Configuration
public class AppConfig {

@Bean
public UserRepository userRepository() {
return new InMemoryUserRepository();
}

@Bean
public UserService userService() {
return new UserService(userRepository());
}
}
Step 3: Use the IoC Container to Manage Beans

import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
// Create an IoC container
ApplicationContext context = new
AnnotationConfigApplicationContext([Link]);

// Get the UserService bean from the container


UserService userService = [Link]([Link]);

// Use the bean


[Link]("Amaan");
}
}

Key Points and Features of IoC in Spring

1. Automatic Bean Management:


o The IoC container automatically handles the instantiation, configuration, and lifecycle
management of beans.
2. Dependency Injection:
o Dependencies between beans are automatically injected by the container, promoting loose
coupling between components.
3. Flexibility in Configuration:
o Spring allows beans to be configured using XML, annotations, or Java-based configuration. This
flexibility lets you choose the best approach for your application.
4. Centralized Configuration:
o All bean definitions and configurations are centralized, making it easier to manage and
understand the application's structure.
5. Support for Different Scopes:
o The IoC container supports different bean scopes, such as singleton, prototype, request,
session, and global session, to control the lifecycle and visibility of beans.
6. Event Handling:
o The IoC container supports event handling, where beans can listen to application events and
respond accordingly.
7. Declarative Support:
o The IoC container provides declarative support for transactions, security, and other concerns
through annotations and XML configurations.

Advantages of IoC

1. Loose Coupling:
o IoC promotes loose coupling by decoupling the implementation of objects from their
dependencies.
2. Better Testability:
o Since dependencies are injected, it is easier to replace them with mock objects during unit
testing.
3. Cleaner Code:
o IoC helps in writing cleaner, more maintainable code by reducing boilerplate code related to
object creation and management.
4. Flexibility and Scalability:
o IoC allows you to easily reconfigure and scale your application by simply changing the
configuration without altering the code.

Conclusion

Inversion of Control is a fundamental concept in the Spring Framework that enables the development of loosely
coupled, maintainable, and scalable applications. By understanding and utilizing IoC, you can delegate the
management of object creation and dependency resolution to the Spring container, allowing you to focus on the
business logic of your application.

Spring Framework: AOP, Bean Scopes, Autowiring, and Annotations


1. Aspect-Oriented Programming (AOP)

Aspect-Oriented Programming (AOP) in Spring is a programming paradigm that allows you to separate
cross-cutting concerns (like logging, transaction management, security) from the business logic. AOP enables
you to apply these concerns declaratively, usually by applying "aspects" to your code.

Key Concepts:

• Aspect: A module that encapsulates a cross-cutting concern.


• Join Point: A point in the application where an aspect can be applied (e.g., method execution).
• Advice: The action taken by an aspect at a particular join point (e.g., before, after, around).
• Pointcut: A set of join points where an advice should be applied.
• Weaving: The process of applying aspects to the target object.

Example of AOP with Logging:

import [Link];
import [Link];
import [Link];

@Aspect
@Component
public class LoggingAspect {
@Before("execution(* [Link].*.*(..))")
public void logBeforeMethodExecution() {
[Link]("Logging before method execution");
}
}

// Service class
@Component
public class UserService {
public void registerUser(String username) {
[Link]("Registering user: " + username);
}
}

// Main class to run the application


import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext([Link]);
UserService userService = [Link]([Link]);
[Link]("Amaan");
}
}

// Configuration class
import [Link];
import [Link];
import [Link];

@Configuration
@ComponentScan("[Link]")
@EnableAspectJAutoProxy
public class AppConfig {
}

2. Bean Scopes

Bean scope in Spring defines the lifecycle and visibility of a bean in the context of a Spring application.

1. Singleton:

• Description: Only one instance of the bean is created for the entire Spring IoC container.
• Use Case: Shared components, services.
• Default Scope: Singleton is the default scope.

Example:

import [Link];
import [Link];

@Component
@Scope("singleton")
public class SingletonBean {
public SingletonBean() {
[Link]("SingletonBean instance created");
}
}

2. Prototype:

• Description: A new instance of the bean is created every time it is requested from the container.
• Use Case: Stateful beans where you need a new instance for each request.

Example:

import [Link];
import [Link];

@Component
@Scope("prototype")
public class PrototypeBean {
public PrototypeBean() {
[Link]("PrototypeBean instance created");
}
}
3. Request:

• Description: A new bean instance is created for each HTTP request. It is available only in the context of
web applications.
• Use Case: Beans with a lifecycle tied to a single HTTP request.

Example:

import [Link];
import [Link];
import [Link];

@Component
@RequestScope
public class RequestBean {
public RequestBean() {
[Link]("RequestBean instance created for each HTTP request");
}
}

4. Session:

• Description: A new bean instance is created for each HTTP session. Available only in the context of
web applications.
• Use Case: Beans that need to maintain state across multiple requests within a session.

Example:

import [Link];
import [Link];
import [Link];

@Component
@SessionScope
public class SessionBean {
public SessionBean() {
[Link]("SessionBean instance created for each HTTP session");
}
}

5. Application:

• Description: A single bean instance is created for the entire lifecycle of a web application. Shared
across all requests and sessions.
• Use Case: Shared resources like caches or singletons that need to be available across the entire
application.

Example:

import [Link];
import [Link];
import [Link];

@Component
@ApplicationScope
public class ApplicationBean {
public ApplicationBean() {
[Link]("ApplicationBean instance created for the entire
application");
}
}

6. WebSocket:

• Description: A new bean instance is created for each WebSocket session.


• Use Case: Beans that need to maintain state for the duration of a WebSocket connection.

Example:

import [Link];
import [Link];
import [Link];

@Component
@Scope("websocket")
@EnableWebSocket
public class WebSocketBean {
public WebSocketBean() {
[Link]("WebSocketBean instance created for each WebSocket session");
}
}

3. Autowiring

Autowiring in Spring allows the Spring container to automatically resolve and inject dependencies into beans.

Types of Autowiring:

• @Autowired: Automatically injects the required dependency by type.


• @Qualifier: Used along with @Autowired to resolve ambiguity when there are multiple beans of the
same type.
• @Primary: Marks a bean as the primary candidate when multiple beans of the same type are available.

Example of Autowiring with @Autowired and @Qualifier:

import [Link];
import [Link];
import [Link];

@Component
public class UserService {
private final UserRepository userRepository;

@Autowired
public UserService(@Qualifier("inMemoryUserRepository") UserRepository
userRepository) {
[Link] = userRepository;
}

public void registerUser(String username) {


[Link](new User(username));
}
}

4. Annotations
Spring Framework heavily relies on annotations for configuration, making the code cleaner and more readable.

Common Annotations:

1. @Component:
o Marks a class as a Spring bean.

@Component
public class MyComponent {
// Bean logic
}

2. @Service:
o A specialization of @Component for service layer beans.

@Service
public class UserService {
// Service logic
}

3. @Repository:
o A specialization of @Component for DAO (Data Access Object) beans.

@Repository
public class UserRepositoryImpl implements UserRepository {
// Data access logic
}

4. @Controller:
o A specialization of @Component for web controllers.

@Controller
public class UserController {
// Web controller logic
}

5. @RestController:
o Combines @Controller and @ResponseBody to create RESTful web services.

@RestController
public class UserController {
@GetMapping("/users")
public List<User> getUsers() {
// RESTful service logic
}
}

6. @Configuration:
o Marks a class as a source of bean definitions. Used for Java-based configuration.

@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserService(userRepository());
}
@Bean
public UserRepository userRepository() {
return new InMemoryUserRepository();
}
}

7. @Bean:
o Indicates that a method produces a bean to be managed by the Spring container.

@Bean
public UserService userService() {
return new UserService();
}

8. @Qualifier:
o Used to specify which bean should be autowired when multiple beans of the same type exist.

@Autowired
@Qualifier("specificBean")
private UserRepository userRepository;

9. @Primary:
o Marks a bean as the primary candidate when multiple beans of the same type exist.

@Primary
@Bean
public UserRepository userRepository() {
return new InMemoryUserRepository();
}

Key Points and Features

• AOP: Allows modularizing cross-cutting concerns, making the code cleaner and more maintainable.
• Bean Scopes: Different scopes manage bean lifecycles, from singleton to request or session-scoped
beans, providing flexibility in resource management.
• Autowiring: Simplifies dependency injection, reducing the boilerplate code required for manual wiring.
• Annotations: Provide a declarative way of configuring Spring beans, leading to more concise and
readable code.

Conclusion

The Spring Framework offers powerful tools like AOP, various bean scopes, autowiring, and annotations,
which together enable developers to build robust, scalable, and maintainable applications. Understanding these
concepts will significantly enhance your ability to work effectively with Spring and leverage its capabilities to
the fullest.
Spring Bean Lifecycle Callbacks
In Spring, beans go through a lifecycle managed by the Spring IoC container. The lifecycle includes creation,
initialization, and destruction. Spring provides several ways to hook into these phases of the bean lifecycle,
allowing you to run custom logic during bean initialization and destruction.

Key Concepts in Bean Lifecycle Callbacks

1. Initialization:
o Occurs after the bean is instantiated and dependencies are injected. Custom initialization logic
can be added here.
2. Destruction:
o Happens when the Spring container is shut down. Custom cleanup logic can be added here.

Ways to Implement Lifecycle Callbacks

1. Using @PostConstruct and @PreDestroy Annotations


2. Implementing InitializingBean and DisposableBean Interfaces
3. Using init-method and destroy-method Attributes in XML Configuration
4. Using Java-based Configuration (@Bean with initMethod and destroyMethod)

1. Using @PostConstruct and @PreDestroy Annotations

Example:

import [Link];
import [Link];
import [Link];

@Component
public class MyBean {

public MyBean() {
[Link]("Bean is being created");
}

@PostConstruct
public void init() {
[Link]("Bean is being initialized");
}

@PreDestroy
public void destroy() {
[Link]("Bean is being destroyed");
}
}

Explanation:

• @PostConstruct: This method will be called after the bean's properties have been set.
• @PreDestroy: This method will be called just before the bean is removed from the container.
2. Implementing InitializingBean and DisposableBean Interfaces

Example:

import [Link];
import [Link];
import [Link];

@Component
public class AnotherBean implements InitializingBean, DisposableBean {

public AnotherBean() {
[Link]("AnotherBean is being created");
}

@Override
public void afterPropertiesSet() {
[Link]("AnotherBean is being initialized");
}

@Override
public void destroy() {
[Link]("AnotherBean is being destroyed");
}
}

Explanation:

• afterPropertiesSet(): Called after the bean's properties have been set, similar to @PostConstruct.
• destroy(): Called before the bean is destroyed, similar to @PreDestroy.

3. Using Java-based Configuration (@Bean with initMethod and destroyMethod)

Example:

java
Copy code
import [Link];
import [Link];

@Configuration
public class AppConfig {

@Bean(initMethod = "customInit", destroyMethod = "customDestroy")


public JavaConfigBean javaConfigBean() {
return new JavaConfigBean();
}
}

public class JavaConfigBean {

public void customInit() {


[Link]("JavaConfigBean is being initialized");
}

public void customDestroy() {


[Link]("JavaConfigBean is being destroyed");
}
}
Explanation:

• Similar to XML configuration, but using Java-based configuration.


• initMethod: Defines the initialization method.
• destroyMethod: Defines the destruction method.

Key Points and Features

• Post Initialization and Pre Destruction Hooks: Allows for custom logic to be executed at specific
lifecycle stages.
• Multiple Approaches: Spring provides multiple ways to implement lifecycle callbacks, giving
flexibility in how you manage the bean lifecycle.
• Order of Execution:
1. Constructor is called.
2. Dependencies are injected.
3. @PostConstruct or afterPropertiesSet() is called.
4. The bean is ready to be used.
5. @PreDestroy or destroy() is called when the container is shut down.

Advantages

• Resource Management: Allows for proper initialization and cleanup of resources, like opening and
closing database connections.
• Decoupling: Separation of the main business logic from resource management code.
• Flexibility: Can be easily configured using annotations, interfaces, or XML/Java configurations.

Conclusion

Understanding the lifecycle callbacks in Spring is essential for managing resources efficiently and ensuring that
your beans are correctly initialized and cleaned up. Whether you use annotations, interfaces, or configuration,
Spring gives you the tools to control the lifecycle of your beans effectively.

Bean Configuration styles


Spring Framework provides multiple styles for bean configuration, each catering to different preferences and
needs. These styles allow you to define and configure beans in your Spring application context. Here’s a
rundown of the main configuration styles:

1. XML-Based Configuration

XML-based configuration was the traditional way to configure Spring beans before annotations and Java-based
configurations became popular.

Key Points:

• Declarative: Uses XML files to define bean configurations.


• Separation of Concerns: Configuration is separated from code.
• Less Flexible: Less type-safe compared to annotations and Java-based configuration.
2. Annotation-Based Configuration

Annotation-based configuration simplifies bean configuration by using annotations to declare beans and their
dependencies.

Key Points:

• Compact: Reduces the amount of XML configuration.


• Modern: Preferred in modern Spring applications.
• Automatic Scanning: Allows for automatic detection of beans through component scanning.

Example:

// [Link]
package [Link];

import [Link];

@Component
public class MyBean {
private String name;

public void setName(String name) {


[Link] = name;
}

public void printName() {


[Link]("Bean name: " + name);
}
}

// [Link]
import [Link];
import [Link];

@Configuration
@ComponentScan("[Link]")
public class AppConfig {
}

// [Link]
import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext([Link]);
MyBean myBean = [Link]([Link]);
[Link]();
}
}

3. Java-Based Configuration

Java-based configuration is a modern way to configure Spring beans using Java classes and methods.
Key Points:

• Type-Safe: Provides compile-time safety.


• Flexible: Allows for dynamic and programmatic bean configuration.
• Preferred in Modern Applications: Offers better refactoring and IDE support compared to XML.

Example:

// [Link]
package [Link];

public class MyBean {


private String name;

public void setName(String name) {


[Link] = name;
}

public void printName() {


[Link]("Bean name: " + name);
}
}

// [Link]
import [Link];
import [Link];

@Configuration
public class AppConfig {

@Bean
public MyBean myBean() {
MyBean myBean = new MyBean();
[Link]("Spring JavaConfig");
return myBean;
}
}

// [Link]
import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
ApplicationContext context = new
AnnotationConfigApplicationContext([Link]);
MyBean myBean = [Link]([Link]);
[Link]();
}
}

Summary

• XML-Based Configuration: Traditional, declarative, but less flexible and more verbose.
• Annotation-Based Configuration: Modern, compact, and leverages component scanning.
• Java-Based Configuration: Type-safe, flexible, and preferred in modern Spring applications.
• Combination: Allows leveraging both XML and annotations for a more flexible configuration
approach.
Each configuration style offers unique advantages and can be chosen based on the specific needs and constraints
of your application. In modern Spring development, Java-based and annotation-based configurations are
generally preferred for their flexibility and maintainability.

Spring Boot
Spring Boot Overview

Spring Boot is a project from the Spring team that simplifies the setup and development of new Spring
applications. It builds on top of the Spring Framework by providing a set of conventions, defaults, and
automated configurations that reduce the amount of boilerplate code and configuration needed to get an
application up and running.

Key Features of Spring Boot

1. Auto-Configuration:
o Automatically configures your Spring application based on the dependencies on the classpath.
2. Standalone:
o Spring Boot applications are standalone and can be run from the command line, eliminating the
need for a separate server configuration.
3. Embedded Servers:
o Includes embedded servers (like Tomcat, Jetty, and Undertow) so you can run your application
directly without needing an external server.
4. Production-Ready:
o Provides built-in support for features like health checks and metrics, which are useful for
monitoring and managing applications in production.
5. Convention over Configuration:
o Follows a set of default configurations to minimize the amount of setup needed.
6. Microservices Ready:
o Simplifies building and deploying microservices architectures.

Creating a Simple Spring Boot Application

1. Using Spring Initializr

Spring Initializr is a web-based tool for generating a basic Spring Boot project structure.

• URL: Spring Initializr


• Steps:
o Select the project metadata (Group, Artifact, Name).
o Choose dependencies (e.g., Spring Web, Spring Data JPA, Thymeleaf).
o Generate the project and download the ZIP file.

2. Basic Spring Boot Application Example

Project Structure:

• src/main/java/com/example/demo/[Link]
• src/main/resources/[Link]
Application Code:

{
// [Link]
package [Link];

------------
------------
//Application code goes here

Configuration File:

# [Link]
[Link]=8080

Running the Application:

• Execute the main method in DemoApplication or use the mvn spring-boot:run command if using
Maven.

3. Spring Boot with Data Access

Adding Dependencies:

// Dependency XML code

Entity Class:

// Entity Class Code

Repository Interface:

{
// Repository Interface code
}

Service Layer:

// Service Layer code

Controller Layer:

// Controller Layer code

Configuration for Data Source:

// Configuration code

Key Points and Features

1. Auto-Configuration: Spring Boot automatically configures your application based on the dependencies
you include.
2. Embedded Servers: You can package your application as a JAR or WAR file with an embedded server.
3. Production-Ready: Features like health checks, metrics, and application monitoring are built-in.
4. Conventions: Defaults and sensible conventions reduce the need for explicit configuration.
5. Microservices Support: Integration with Spring Cloud and other tools for building microservices.

Conclusion

Spring Boot simplifies the development of Spring applications by providing a range of features that reduce
boilerplate code and configuration. Its support for embedded servers, auto-configuration, and production-ready
features makes it a powerful tool for building modern applications.

Spring Boot Build Systems


Spring Boot supports various build systems to manage dependencies, compile code, and package applications.
The two most popular build systems used with Spring Boot are Maven and Gradle. Each build system has its
own set of features and configuration styles.

1. Maven

Maven is a widely-used build automation tool that uses XML-based configuration ([Link]) to manage project
dependencies, build, and packaging.

Key Points:

• XML Configuration: Uses [Link] to define dependencies, plugins, and build configurations.
• Dependency Management: Handles dependencies and their transitive dependencies.
• Standard Lifecycle: Provides a standard build lifecycle including phases like compile, test, package,
and install.

2. Gradle

Gradle is a versatile build automation tool that uses Groovy or Kotlin DSL for configuration. It is known for its
performance and flexibility.

Key Points:

• DSL Configuration: Uses [Link] (Groovy) or [Link] (Kotlin) for configuration.


• Incremental Builds: Supports incremental builds to improve build performance.
• Flexible: Allows custom build logic and plugins.

Comparison and Features

• Maven:
o XML Configuration: Clear and declarative.
o Standard Build Lifecycle: Provides a fixed lifecycle with predefined phases.
o Dependency Management: Good for managing complex dependencies with transitive support.
• Gradle:
o DSL Configuration: Flexible and concise using Groovy or Kotlin.
o Incremental Builds: Faster build times due to incremental builds.
o Customization: High level of customization and extensibility.
o Parallel Execution: Supports parallel execution for faster builds.
Spring Boot Build System Best Practices

1. Consistency: Choose a build system (Maven or Gradle) and use it consistently across your projects to
simplify build and dependency management.
2. Version Management: Use Spring Boot’s dependency management features to avoid version conflicts
and ensure compatibility.
3. Testing: Include testing dependencies and configurations in your build script to ensure quality.
4. Packaging: Utilize the Spring Boot plugins to package your application as an executable JAR or WAR
file for deployment.

Conclusion

Both Maven and Gradle are powerful build tools for managing Spring Boot applications. Maven provides a
standard and widely-used approach with XML configuration, while Gradle offers flexibility and performance
with its DSL configuration. The choice between Maven and Gradle often comes down to personal or team
preference and the specific needs of your project.

Spring Boot Code Structure


Typical Project Structure

Here’s a common directory structure for a Spring Boot application:

myapp/

├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── myapp/
│ │ │ ├── [Link]
│ │ │ ├── controller/
│ │ │ │ └── [Link]
│ │ │ ├── service/
│ │ │ │ └── [Link]
│ │ │ ├── repository/
│ │ │ │ └── [Link]
│ │ │ └── model/
│ │ │ └── [Link]
│ │ └── resources/
│ │ ├── [Link]
│ │ └── static/
│ │ └── assets/
│ │ └── templates/
│ │ └── [Link]
│ └── test/
│ ├── java/
│ │ └── com/
│ │ └── example/
│ │ └── myapp/
│ │ └── [Link]
│ └── resources/

├── .gitignore
├── [Link]
└── [Link]

1. src/main/java Directory

This directory contains the main application code.

• [Link]: The main class annotated with @SpringBootApplication, which is the


• controller/: Contains REST controllers or MVC controllers that handle HTTP requests and responses.
• service/: Contains business logic services. Services are used by controllers and interact with
repositories.
• repository/: Contains Spring Data JPA repositories or other data access layers.
• model/: Contains entity classes or data models.

2. src/main/resources Directory

This directory contains configuration files and static resources.

• [Link] or [Link]: Configuration file where you define application-


• static/: Contains static resources such as CSS, JavaScript, and images.
• templates/: Contains Thymeleaf or other templating engine templates for server-side rendering.

3. src/test/java Directory

This directory contains test cases for the application.

• [Link]: A sample test class to verify the context loading.

Key Points and Features

1. Separation of Concerns:
o Controllers: Handle HTTP requests and responses.
o Services: Contain business logic and interact with repositories.
o Repositories: Manage data persistence and retrieval.
o Models: Represent data entities.
2. Configuration:
o Properties Files: Centralize configuration settings.
o Profiles: Use different configurations for different environments (e.g., application-
[Link]).
3. Static and Template Resources:
o Static Resources: Serve static content like images and CSS.
o Templates: Render dynamic content on the server side using templating engines like Thymeleaf.
4. Testing:
o Unit Testing: Test individual components in isolation.
o Integration Testing: Test interactions between components and with the Spring context.
5. Production Readiness:
o Health Checks: Monitor application health with Spring Boot Actuator.
o Metrics: Collect and monitor application metrics.
Conclusion

A well-structured Spring Boot project enhances maintainability and clarity. By organizing code into controllers,
services, repositories, and models, and by managing configurations and resources effectively, you can build
scalable and maintainable applications. Additionally, proper testing and monitoring ensure that your application
remains robust and reliable.

Spring Boot Runners and Logging


Spring Boot provides features to manage application startup and logging effectively. Here’s an overview of
how to use runners to execute code at startup and logging to monitor application behavior.

1. Spring Boot Runners

Spring Boot Runners are used to execute code after the application context has been initialized but before the
application is fully started. They are useful for tasks like initializing resources or executing startup logic.

Key Points:

1. CommandLineRunner: Interface that runs after the application context is loaded and right before the
Spring Boot application starts.
2. ApplicationRunner: Similar to CommandLineRunner, but provides the ApplicationArguments
interface to access command-line arguments.

2. Spring Boot Logging

Spring Boot provides a logging abstraction that allows you to use different logging frameworks (e.g., Logback,
Log4j2) with ease. By default, Spring Boot uses Logback for logging.

Key Points:

1. Logging Levels: Configurable levels such as TRACE, DEBUG, INFO, WARN, ERROR.
2. Logging Configuration: Managed via [Link] or [Link].
3. Custom Loggers: You can create custom loggers in your classes.

Conclusion

• Runners: Use CommandLineRunner and ApplicationRunner to execute startup logic and initialize
resources after the Spring application context is loaded.
• Logging: Configure logging levels and outputs using [Link], logback-
[Link], or other logging frameworks. Spring Boot simplifies logging with default configurations
and allows customization.

These features help in managing application initialization and monitoring behavior efficiently

Building RESTful Web Services with Spring Boot


Spring Boot makes it straightforward to build RESTful web services thanks to its built-in support for handling
HTTP requests and responses. Below are key concepts, features, and examples for creating RESTful web
services using Spring Boot.
Key Concepts

1. RESTful Web Services: Use HTTP methods (GET, POST, PUT, DELETE) to interact with resources.
2. Controllers: Define endpoints and handle requests.
3. Request and Response Handling: Map HTTP requests to methods and format responses.
4. Exception Handling: Handle errors and provide meaningful responses.
5. Data Binding: Convert HTTP request data to Java objects and vice versa.

Features

1. Annotations: Use annotations to define RESTful endpoints and manage request mappings.
2. JSON Support: Automatically serialize and deserialize Java objects to/from JSON.
3. Exception Handling: Centralized error handling with @ControllerAdvice.
4. Validation: Validate request data using annotations like @Valid and @NotNull.
5. Pagination and Sorting: Easily implement pagination and sorting with Spring Data.

Conclusion

• RESTful Endpoints: Define RESTful services using @RestController and mapping annotations
(@GetMapping, @PostMapping, etc.).
• Service Layer: Encapsulates business logic.
• Repository Layer: Manages data access with Spring Data JPA.
• Exception Handling: Provides a way to handle and respond to errors.
• Validation: Ensures data integrity using validation annotations.

Spring Boot simplifies the development of RESTful web services with powerful abstractions and features

Spring Boot REST Controller


A REST Controller in Spring Boot is a class annotated with @RestController that handles HTTP requests
and responses. It is a key component in building RESTful web services.

Key Points

1. Annotation: @RestController is a specialization of @Controller and @ResponseBody, which means


it combines @Controller and @ResponseBody to handle RESTful requests and responses.
2. Request Mapping: Use annotations such as @RequestMapping, @GetMapping, @PostMapping,
@PutMapping, and @DeleteMapping to map HTTP requests to handler methods.
3. Response Body: Automatically serializes Java objects to JSON or XML format for HTTP responses.
4. Path Variables: Extract values from the URI using @PathVariable.
5. Request Parameters: Extract parameters from the query string or form data using @RequestParam.
6. Request Body: Bind HTTP request bodies to Java objects using @RequestBody.

Features
• Automatic JSON Serialization: Converts Java objects to JSON and vice versa using Jackson (or
another JSON library).
• Exception Handling: Handle errors and return custom error responses.
• Data Binding: Bind request parameters and body to Java objects.
• HTTP Status Codes: Return appropriate HTTP status codes in responses.

Conclusion

• REST Controllers in Spring Boot handle HTTP requests and responses in a RESTful manner.
• Annotations like @RestController, @RequestMapping, @GetMapping, @PostMapping, etc., define the
behavior of endpoints.
• Exception Handling and custom status codes provide robust error management and meaningful HTTP
responses.
• Data Binding simplifies the conversion between HTTP requests and Java objects.

Spring Boot’s support for building RESTful web services streamlines development and helps create scalable
and maintainable applications

Request Mapping in Spring Boot


Request Mapping in Spring Boot is used to map HTTP requests to handler methods in a controller. This
mechanism enables you to handle various types of HTTP requests (GET, POST, PUT, DELETE, etc.) and map
them to specific methods in your controller classes.

Key Points

1. @RequestMapping: The primary annotation used for mapping HTTP requests to specific methods. It can
be used at the class and method levels.
2. HTTP Methods: You can specify the HTTP method (GET, POST, PUT, DELETE) using method
attribute of @RequestMapping.
3. Path Variables: Use {} syntax to define path variables within the URL.
4. Request Parameters: Use @RequestParam to extract query parameters from the URL.
5. Request Body: Use @RequestBody to bind the HTTP request body to a Java object.
6. Headers: Use the headers attribute to specify which headers should be present in the request.

Features

• Flexible URL Mapping: You can map URLs with various patterns and parameters.
• Custom Methods: Handle different HTTP methods (GET, POST, etc.) using method-specific
annotations.
• Path Variables: Extract dynamic values from the URL.
• Request Parameters: Handle query parameters for additional data.
• Request Body: Bind incoming JSON or XML to Java objects.

Conclusion

• Request Mapping allows you to define and customize how HTTP requests are routed to your controller
methods.
• Annotations like @RequestMapping, @GetMapping, @PostMapping, etc., provide flexibility for
handling different types of requests.
• Path Variables and Request Parameters help in extracting dynamic values and query data from the
URL.
• Request Body facilitates binding incoming request payloads to Java objects.
• Headers extraction allows you to work with HTTP headers.

These features make Spring Boot's @RequestMapping a powerful tool for building RESTful web services

Request Body in Spring Boot

Request Body in Spring Boot is used to bind the HTTP request body to a Java object. This is particularly useful
for handling data sent in the body of HTTP POST, PUT, or PATCH requests.

Key Points

1. Binding to Java Objects: Automatically maps JSON or XML request bodies to Java objects.
2. @RequestBody Annotation: Used in controller methods to specify that a method parameter should be
bound to the body of the HTTP request.
3. Content Type: The request body is typically in JSON or XML format, and the content type should be
specified in the Content-Type header of the request.
4. Validation: You can validate the bound objects using validation annotations.
5. Serialization/Deserialization: Jackson (or another library) handles the conversion between JSON/XML
and Java objects.

Features

• Automatic Conversion: Converts JSON/XML payloads into Java objects.


• Validation: Supports Bean Validation (JSR-380) for validating request data.
• Exception Handling: Automatically handles errors related to data binding and validation.
• Flexible Data Handling: Supports various content types (JSON, XML, etc.).

Conclusion

• Request Body Binding allows you to map incoming JSON or XML data directly to Java objects using
@RequestBody.
• Validation can be applied to ensure that data meets specific criteria using validation annotations.
• Complex Objects and nested structures can be handled seamlessly.
• Custom Error Handling ensures that errors related to data binding or validation are managed
gracefully.

Spring Boot’s support for request body binding simplifies the development of RESTful services by automating
the conversion between HTTP requests and Java objects.

Path Variable in Spring Boot


Path Variable is used to capture values from the URI path in HTTP requests. This feature is useful when you
need to pass dynamic values in the URL, such as resource IDs or other identifiers.

Key Points

1. Annotation: @PathVariable is used to bind a method parameter to a URI template variable.


2. Dynamic Values: Allows you to capture and use dynamic values from the URL.
3. URI Template: Use {} to define placeholders in the URI path.
4. Multiple Path Variables: You can use multiple path variables in a single URI.
5. Optional Variables: You can provide default values or handle cases where path variables might be
missing.

Features

• Flexible URI Mapping: Allows you to map dynamic segments of the URL to method parameters.
• Easy Data Extraction: Automatically extracts values from the URL and binds them to method
parameters.
• Supports Multiple Variables: Handle complex URL patterns with multiple path variables.

Conclusion

• Path Variables in Spring Boot are used to capture dynamic parts of the URL and bind them to method
parameters.
• Annotations like @PathVariable enable flexible and dynamic URI mappings.
• Multiple Variables and optional variables can be handled seamlessly.
• Default Values for path variables ensure robust handling of missing values.

Spring Boot’s support for path variables makes it easy to build RESTful services with dynamic and flexible
URL structures.

Request Parameter in Spring Boot


Request Parameter is used to extract parameters from the query string or form data in HTTP requests. This
feature is useful for handling additional data sent as part of the URL query or form submissions.

Key Points

1. Annotation: @RequestParam is used to bind request parameters to method parameters in a controller.


2. Query Parameters: Typically extracted from the URL query string (?key=value).
3. Default Values: You can provide default values if the parameter is not present in the request.
4. Required Parameter: You can specify whether a parameter is required or optional.
5. Multiple Parameters: You can handle multiple query parameters in a single request.

Features

• Flexible Parameter Binding: Binds query parameters from the URL to method parameters.
• Default Values: Allows specifying default values if the parameter is not provided.
• Optional Parameters: Supports optional parameters to handle cases where parameters might be
missing.
• Multiple Parameters: Handles multiple parameters and complex query strings.

1. Basic Request Parameter

[Link]:
Example Request:

GET /users/search?name=Alice

Example Response:

Searching for user: Alice

2. Default Values

[Link]:

Example Requests:

• With category:

GET /products/list?category=electronics

Response:

Listing products in category: electronics

• Without category:

GET /products/list

Response:

Listing products in category: all

3. Optional Parameters

[Link]:

Example Requests:

• With status:

GET /orders/status?status=shipped

Response:

Order status: shipped

• Without status:

GET /orders/status

Response:

No status specified

4. Handling Multiple Parameters


[Link]:

Example Request:

GET /search?keyword=java&page=2

Example Response:

Searching for: java on page: 2

Example Request (default page):

GET /search?keyword=java

Example Response:

Searching for: java on page: 1

Conclusion

• Request Parameters are used to extract and bind query parameters from the URL to method parameters
using @RequestParam.
• Default Values ensure that methods can handle missing parameters gracefully.
• Optional Parameters allow flexibility in handling queries without requiring all parameters to be
present.
• Multiple Parameters can be managed seamlessly for more complex queries.

Spring Boot's support for request parameters simplifies the handling of dynamic query data and enables flexible
API designs.

HTTP Methods in Spring Boot: GET, POST, PUT, DELETE


In RESTful APIs, HTTP methods are used to perform various operations on resources. Spring Boot provides
specific annotations for each HTTP method to handle different types of requests.

1. GET Request

Purpose: Retrieve data from the server. GET requests are used to fetch data without modifying it.

Key Points:

• Idempotent: Multiple identical GET requests will have the same effect as a single request.
• No Request Body: GET requests do not have a request body; data is usually passed through the URL.

Example:

[Link]:

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@RestController
@RequestMapping("/users")
public class UserController {

@GetMapping("/{id}")
public String getUserById(@PathVariable("id") Long id) {
return "User ID: " + id;
}
}

Explanation:

• @GetMapping("/{id}"): Maps GET requests to /users/{id} to the getUserById method.


• @PathVariable("id"): Binds the id from the URL to the method parameter.

Example Request:

GET /users/123

Example Response:

User ID: 123

2. POST Request

Purpose: Create a new resource on the server. POST requests are used to send data to the server for creating or
updating resources.

Key Points:

• Not Idempotent: Multiple identical POST requests may result in multiple resource creations.
• Request Body: Data is usually sent in the body of the request.

Example:

[Link]:

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@RestController
@RequestMapping("/users")
public class UserController {

@PostMapping
public String createUser(@RequestBody User user) {
return "User created: " + [Link]();
}
}

Explanation:

• @PostMapping: Maps POST requests to /users to the createUser method.


• @RequestBody User user: Binds the JSON request body to a User object.

Example Request (JSON):

{
"name": "Alice",
"age": 30
}

Example Response:

User created: Alice

3. PUT Request

Purpose: Update an existing resource on the server. PUT requests are used to send data to the server to update a
resource.

Key Points:

• Idempotent: Multiple identical PUT requests will have the same effect as a single request.
• Request Body: Data to update the resource is usually sent in the body of the request.

Example:

[Link]:

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@RestController
@RequestMapping("/users")
public class UserController {

@PutMapping("/{id}")
public String updateUser(@PathVariable("id") Long id, @RequestBody User user) {
return "User ID: " + id + " updated to name: " + [Link]();
}
}

Explanation:

• @PutMapping("/{id}"): Maps PUT requests to /users/{id} to the updateUser method.


• @PathVariable("id"): Binds the id from the URL to the method parameter.
• @RequestBody User user: Binds the JSON request body to a User object.

Example Request (JSON):

{
"name": "Bob",
"age": 35
}

Example Response:

User ID: 123 updated to name: Bob

4. DELETE Request

Purpose: Delete an existing resource on the server. DELETE requests are used to remove a resource.

Key Points:

• Idempotent: Multiple identical DELETE requests will have the same effect as a single request.
• No Request Body: DELETE requests typically do not have a request body.

Example:

[Link]:

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

@RestController
@RequestMapping("/users")
public class UserController {

@DeleteMapping("/{id}")
public String deleteUser(@PathVariable("id") Long id) {
return "User ID: " + id + " deleted";
}
}

Explanation:

• @DeleteMapping("/{id}"): Maps DELETE requests to /users/{id} to the deleteUser method.


• @PathVariable("id"): Binds the id from the URL to the method parameter.

Example Request:

DELETE /users/123

Example Response:

User ID: 123 deleted


Summary of Features

• GET: Retrieve data; idempotent; no request body.


• POST: Create a new resource; not idempotent; request body required.
• PUT: Update an existing resource; idempotent; request body required.
• DELETE: Remove a resource; idempotent; no request body.

These HTTP methods provide a foundation for building RESTful APIs by allowing CRUD (Create, Read,
Update, Delete) operations on resources.

Building Web Applications with Spring Boot and Spring Framework

Spring Boot and Spring Framework provide a powerful set of tools for developing web applications. Below, I’ll
outline the key steps and provide examples for building a web application using both Spring Boot and Spring
Framework APIs in Java.

1. Setting Up Your Spring Boot Project

Spring Boot simplifies the setup and configuration of your application. You can use Spring Initializr to create a
new project.

Using Spring Initializr

1. Go to Spring Initializr.
2. Select the following options:
o Project: Maven or Gradle
o Language: Java
o Spring Boot Version: (Choose the latest stable version)
o Group: [Link]
o Artifact: myapp
o Dependencies:
▪ Spring Web
▪ Spring Data JPA (if you need database access)
▪ Thymeleaf (if you want server-side templating)
▪ H2 Database (for a simple in-memory database)
3. Click Generate.

Download the generated ZIP file and extract it. Import the project into your IDE (e.g., IntelliJ IDEA or
Eclipse).

2. Create a Simple Web Controller

Spring Boot uses @RestController for REST APIs or @Controller for traditional web controllers.

Example: Creating a REST Controller

[Link]:

package [Link];

import [Link];
import [Link];
import [Link];

@RestController
@RequestMapping("/api")
public class GreetingController {

@GetMapping("/greet")
public String greet() {
return "Hello, World!";
}
}

Example: Creating a Thymeleaf Controller

[Link]:

package [Link];

import [Link];
import [Link];
import [Link];

@Controller
public class HomeController {

@GetMapping("/")
public String home(Model model) {
[Link]("message", "Welcome to Spring Boot!");
return "home";
}
}

src/main/resources/templates/[Link]:

<!DOCTYPE html>
<html xmlns:th="[Link]
<head>
<title>Home</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>

3. Configure Your Application

[Link] (located in src/main/resources) is used to configure your application.

Example: Configuring Server Port and Database

[Link]=8081

# H2 Database configuration
[Link]=jdbc:h2:mem:testdb
[Link]-class-name=[Link]
[Link]=sa
[Link]=password
[Link]=true
4. Connect to a Database (Optional)

If you need database access, use Spring Data JPA.

Example: Creating an Entity and Repository

[Link]:

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

@Entity
public class User {

@Id
@GeneratedValue(strategy = [Link])
private Long id;
private String name;

// Getters and setters


}

[Link]:

package [Link];

import [Link];
import [Link];

public interface UserRepository extends JpaRepository<User, Long> {


}

Example: Creating a Service and Controller

[Link]:

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

@Service
public class UserService {

@Autowired
private UserRepository userRepository;

public List<User> getAllUsers() {


return [Link]();
}

public User saveUser(User user) {


return [Link](user);
}
}

[Link]:

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

@RestController
@RequestMapping("/users")
public class UserController {

@Autowired
private UserService userService;

@GetMapping
public List<User> getAllUsers() {
return [Link]();
}

@PostMapping
public User createUser(@RequestBody User user) {
return [Link](user);
}
}

5. Running Your Application

Run the application from your IDE or using the command line:

./mvnw spring-boot:run

Or:

./gradlew bootRun

6. Testing Your Application

REST API Testing:

• Using cURL or Postman: Send requests to [Link] or


[Link]

Web Application Testing:


• Open your browser and navigate to [Link] to see the Thymeleaf template rendered.

Summary

• Spring Boot simplifies setting up and configuring web applications.


• REST APIs can be created using @RestController and @RequestMapping.
• Thymeleaf provides server-side templating with @Controller and .html templates.
• Spring Data JPA allows easy integration with databases using entities and repositories.

With these steps and examples, you can build a basic web application using Spring Boot and Spring
Framework.

You might also like