0% found this document useful (0 votes)
57 views14 pages

Unit 4 FSD

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)
57 views14 pages

Unit 4 FSD

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
You are on page 1/ 14

Explain Spring Framework Architecture in detail.

Core Components

1. Spring Core Container


o Core: The core module provides the fundamental parts of the framework, including
the Inversion of Control (IoC) and Dependency Injection (DI) features. It uses
BeanFactory and ApplicationContext for bean management.
o Beans: This module provides the BeanFactory, which is a sophisticated
implementation of the factory pattern. It is the core of the Spring IoC container.
o Context: Builds on the core and beans modules and adds support for accessing
objects in a framework-style manner, similar to a JNDI registry. The
ApplicationContext interface is the central interface in this module.
o SpEL (Spring Expression Language): Provides a powerful expression language for
querying and manipulating an object graph at runtime.
2. Data Access/Integration
o JDBC: Simplifies the use of JDBC by providing a layer of abstraction, thus reducing
the amount of boilerplate code.
o ORM (Object-Relational Mapping): Provides integration layers for popular ORM
frameworks like Hibernate, JPA (Java Persistence API), and JDO (Java Data Objects).
o OXM (Object XML Mapping): Offers support for JAXB, Castor, and other XML
binding frameworks.
o JMS (Java Message Service): Facilitates the creation and consumption of messages,
allowing for message-driven POJOs (Plain Old Java Objects).
o Transactions: Provides a consistent abstraction for transaction management. It
supports declarative and programmatic transaction management for classes that
implement special interfaces as well as for all your POJOs.
3. Spring Web
o Web: Provides basic web-oriented integration features, such as multipart file upload
functionality, and the initialization of the IoC container using servlet listeners and a
web-oriented application context.
o Servlet: A module for building robust web applications. It includes the Spring MVC
(Model-View-Controller) framework which provides a clear separation between the
three components.
o Portlet: Facilitates the development of JSR-168 and JSR-286 compliant portlets.
o Struts: Provides support for integrating with the Struts framework.
4. AOP (Aspect-Oriented Programming) and Aspects
o AOP: Allows for aspect-oriented programming in Spring applications. It enables the
definition of cross-cutting concerns, such as transaction management and logging,
through method interceptors and pointcuts.
o Aspects: Provides integration with AspectJ, a powerful and flexible AOP framework.
It allows developers to create aspects in a more declarative manner.
5. Instrumentation
o This module provides class instrumentation support and classloader
implementations to be used in certain application servers. It is typically used in
scenarios where the application needs to monitor and manage resources.
6. Test
o Supports the testing of Spring components with popular testing frameworks like
JUnit and TestNG. It provides utilities and annotations to facilitate testing, such as
@ContextConfiguration to load the Spring context and @Transactional for
transaction management during tests.

Explain some of the most used Spring Boot annotations with an example.

1. @SpringBootApplication

This is a convenience annotation that combines @Configuration,


@EnableAutoConfiguration, and @ComponentScan. It is typically placed on the main class
of a Spring Boot application.

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class MySpringBootApplication {

public static void main(String[] args) {

SpringApplication.run(MySpringBootApplication.class, args);

2. @RestController
This annotation is a combination of @Controller and @ResponseBody. It is used to create
RESTful web services.

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

@RequestMapping("/api")

public class MyRestController {

@GetMapping("/greeting")

public String greeting() {

return "Hello, World!";

3. @RequestMapping

This annotation is used to map web requests to specific handler classes or handler methods.

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

@RestController

@RequestMapping("/api")

public class MyRestController {

@RequestMapping(value = "/hello", method = RequestMethod.GET)

public String sayHello() {

return "Hello!";

}
4. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping

These are specialized versions of @RequestMapping for specific HTTP methods.

import org.springframework.web.bind.annotation.*;

@RestController

@RequestMapping("/api")

public class MyRestController {

@GetMapping("/hello")

public String getHello() {

return "Hello, GET!";

@PostMapping("/hello")

public String postHello() {

return "Hello, POST!";

@PutMapping("/hello")

public String putHello() {

return "Hello, PUT!";

@DeleteMapping("/hello")

public String deleteHello() {

return "Hello, DELETE!";

5. @Autowired
This annotation is used for automatic dependency injection.

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

@Service

public class MyService {

public String serve() {

return "Service";

@RestController

@RequestMapping("/api")

public class MyRestController {

@Autowired

private MyService myService;

@GetMapping("/serve")

public String serve() {

return myService.serve();

6. @Component, @Service, @Repository, @Controller

These annotations are used to mark classes as Spring-managed components.

import org.springframework.stereotype.Component;

@Component

public class MyComponent {

public String getComponent() {


return "Component";

Differences Spring boot and spring mvc


Feature Spring Boot Spring MVC
Simplify Spring application Web application development
Purpose
development using MVC
Configuration Convention over configuration Requires explicit configuration
Includes embedded servers
Embedded Servers Requires external web server
(Tomcat, Jetty)
Starter Dependencies Provides starter dependencies No starter dependencies
Command-Line
Provides a CLI No CLI
Interface
Metrics, health checks, external Requires custom setup for
Production Readiness
config production
Focus on web layer (MVC
Web Layer Focus Full-stack development
pattern)

When to Use Which

• Use Spring Boot if you want to quickly set up a Spring application with minimal
configuration and are looking for an opinionated, production-ready framework that
simplifies deployment and management.
• Use Spring MVC if you need fine-grained control over the configuration of your web
application and are comfortable with managing dependencies and configurations
manually. Spring MVC is suitable for complex web applications that require custom
configurations.

Design and implement simple spring boot program to print “WELCOME TO SPRING BOOT”.

package com.example.welcomespringboot;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication

public class WelcomeSpringBootApplication {


public static void main(String[] args) {

SpringApplication.run(WelcomeSpringBootApplication.class, args);

@RestController

class WelcomeController {

@GetMapping("/")

public String welcome() {

return "WELCOME TO SPRING BOOT";

Explanation:

1. Main Class:
o WelcomeSpringBootApplication: This is the entry point of the Spring Boot
application. The @SpringBootApplication annotation enables auto-
configuration, component scanning, and configuration properties support.
2. REST Controller:
o WelcomeController: This is a simple REST controller with a single endpoint
(/) that returns the message "WELCOME TO SPRING BOOT". The
@RestController annotation makes the class a RESTful web service
controller, and @GetMapping("/") maps HTTP GET requests to the welcome
method.

Bean life cycle


1. Bean Instantiation

• The Spring container instantiates the bean using the class's no-argument constructor
(or a specified constructor).
• This is the stage where the bean object is created but not yet initialized.

2. Populate Bean Properties

• The Spring container injects dependencies as specified in the bean configuration


(XML, annotations, or Java configuration).
• This involves setting values for properties and injecting references to other beans.

3. Bean Name Awareness (Optional)

• If the bean implements the BeanNameAware interface, the setBeanName() method is


called, passing the bean’s ID.

4. Bean Factory Awareness (Optional)

• If the bean implements the BeanFactoryAware interface, the setBeanFactory()


method is called, providing a reference to the BeanFactory that created the bean.

5. Application Context Awareness (Optional)

• If the bean implements the ApplicationContextAware interface, the


setApplicationContext() method is called, giving access to the
ApplicationContext.

6. Pre-Initialization (BeanPostProcessor)

• Beans that implement the BeanPostProcessor interface will have their


postProcessBeforeInitialization() method called before the
afterPropertiesSet() method.

7. InitializingBean Interface (Optional)

• If the bean implements the InitializingBean interface, its afterPropertiesSet()


method is called.

8. Custom Init Method (Optional)

• If a custom initialization method is specified in the bean configuration, it is invoked at


this point.

9. Post-Initialization (BeanPostProcessor)

• The postProcessAfterInitialization() method of the BeanPostProcessor


interface is called after the custom init method.
10. Bean Ready for Use

• The bean is now fully initialized and ready to be used within the application.

11. Bean Destruction (Shut Down Phase)

• When the application context is closed, the bean goes through the destruction phase.
• If the bean implements the DisposableBean interface, the destroy() method is
called.
• Any custom destroy methods specified in the bean configuration are invoked.

12. Custom Destroy Method (Optional)

• If a custom destroy method is specified, it is invoked.

Explain the following with a program: i.Spring Container ii. Dependency


injection

i. Spring Container

The Spring Container is the core of the Spring Framework. It is responsible for managing the
lifecycle and configuration of application objects, known as beans. The container uses
Dependency Injection (DI) to manage the components that make up an application. The two
main types of containers in Spring are:

1. BeanFactory: The simplest container providing basic DI support.


2. ApplicationContext: A more advanced container that extends BeanFactory,
providing additional features such as event propagation, declarative mechanisms to
create a bean, and different ways to look up.

ii. Dependency Injection (DI)

Dependency Injection is a design pattern used to implement IoC (Inversion of Control),


allowing the creation of dependent objects outside of a class and providing those objects to a
class in different ways. This helps in building loosely coupled, testable, and maintainable
code.

Define the Beans

// Service interface

public interface GreetingService {

void sayGreeting();

// Implementation of the service


public class GreetingServiceImpl implements GreetingService {

public void sayGreeting() {

System.out.println("Hello, Spring Framework!");

Configure Beans in the Spring Container

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class AppConfig {

@Bean

public GreetingService greetingService() {

return new GreetingServiceImpl();

Main Application to Use the Spring Container

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringDemoApp {

public static void main(String[] args) {

// Create the Spring container (ApplicationContext)

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

// Retrieve the bean from the container

GreetingService greetingService = context.getBean(GreetingService.class);

// Use the bean

greetingService.sayGreeting();
}

Explain Spring web MVC. Design and implement simple spring web MVC
framework program to display Helloworld.

Spring Web MVC is a framework that is part of the larger Spring Framework. It follows the
Model-View-Controller (MVC) design pattern, which helps in separating the business logic,
presentation logic, and navigation logic in web applications. Here is a brief overview of each
component:

• Model: Represents the application's data and business logic.


• View: Represents the presentation layer (UI) of the application.
• Controller: Handles user input and updates the Model and View accordingly.

Explanation of Components

1. DispatcherServlet: Acts as the front controller in the Spring MVC architecture. It


intercepts incoming requests and delegates them to appropriate controllers.
2. Controller: HelloWorldController handles the request, adds data to the model, and
returns the name of the view to be rendered.
3. Model: In this example, the model is simply a Model object in the sayHello method
where we add an attribute.
4. View: helloworld.jsp displays the data added to the model by the controller.

Create the Controller

Create a controller class under src/main/java/com/example/springmvc.

package com.example.springmvc;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

@Controller

public class HelloWorldController {


@RequestMapping(value = "/", method = RequestMethod.GET)

public String sayHello(Model model) {

model.addAttribute("message", "Hello World!");

return "helloworld";

Create the View

Create a JSP file named helloworld.jsp under src/main/webapp/WEB-INF/views.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>

<html>

<head>

<title>Hello World</title>

</head>

<body>

<h1>${message}</h1>

</body>

</html>

Define Spring Boot. Why should we use Spring Boot Framework? List out
Spring boot features.

What is Spring Boot?

Spring Boot is an open-source framework that is part of the larger Spring ecosystem. It is
designed to simplify the process of creating stand-alone, production-grade Spring-based
applications. Spring Boot does this by providing a range of out-of-the-box configurations and
defaults, which reduces the amount of manual setup required. It allows developers to focus
more on writing business logic rather than on configuring and setting up the application
infrastructure.

Why Should We Use Spring Boot?

1. Simplified Configuration: Spring Boot auto-configures a Spring application based


on the dependencies present in the classpath. This eliminates the need for boilerplate
code and reduces configuration overhead.
2. Stand-alone Applications: Spring Boot makes it easy to create stand-alone
applications that can be run with a simple java -jar command. It embeds web
servers like Tomcat or Jetty, eliminating the need for external application servers.
3. Production-ready Features: It includes many features that make applications
production-ready, such as health checks, metrics, and externalized configuration.
4. Microservices: Spring Boot is particularly well-suited for building microservices due
to its support for RESTful services, embedded servers, and easy integration with
cloud services.
5. Developer Productivity: With Spring Boot, developers can get started quickly and be
more productive, thanks to its conventions and defaults, which follow the "convention
over configuration" principle.
6. Community and Ecosystem: As part of the larger Spring ecosystem, Spring Boot
benefits from a large and active community. There are numerous guides, tutorials, and
plugins available, making it easier to learn and extend.

Spring Boot Features

1. Spring Initializr: A web-based tool for generating Spring Boot projects. It allows
developers to select dependencies and download a ready-to-use project.
2. Auto-Configuration: Automatically configures Spring and third-party libraries based
on the project’s dependencies.
3. Standalone Applications: Easily create stand-alone Spring applications with
embedded servers like Tomcat, Jetty, or Undertow.
4. Production-ready Metrics: Out-of-the-box support for health checks, metrics,
application information, and externalized configuration.
5. Spring Boot CLI: Command Line Interface that allows you to quickly prototype with
Spring Boot applications using Groovy scripts.
6. Spring Boot Starters: Pre-configured templates for common tasks, such as web
development, data access, security, and messaging, which simplify dependency
management.
7. Spring Boot Actuator: Provides production-ready features to help monitor and
manage applications, including endpoints for health checks, metrics, and environment
information.
8. Externalized Configuration: Supports a variety of configuration sources, including
properties files, YAML files, environment variables, and command-line arguments,
which can be used to configure applications.
9. Logging: Provides a default logging configuration and supports various logging
frameworks like Logback, Log4j2, and Java Util Logging.
10. Spring DevTools: Enhances the development experience with features like automatic
restart, live reload, and configurations for faster feedback.
11. Spring Boot Security: Simplifies the integration of Spring Security into the
application by providing auto-configuration for basic authentication, form-based
login, and more.
12. Database Initialization: Supports database initialization with schema generation and
data loading from SQL scripts.

You might also like