Spring tutorial

 Spring Guide

Spring Tutorial - Learn Spring (geeksforgeeks.org)

This guide about Spring is for both newbies and experts. It covers basics and advanced parts of Spring, like Spring Boot, MVC, JDBC, AOP, Security, and more.

What is Spring? Spring is a famous and simple tool for Java, made by Rod Johnson in 2003. It's used to make big applications. It works well with many other tools like Hibernate and Struts, so some people call it a "tool of tools." It has many parts, like IOC, AOP, and MVC.

Why use Spring? Spring is a free Java tool. Rod Johnson made it, and it started in June 2003. Spring is light and easy to see through. Its basic version is about 2MB. You can use Spring to make any Java program. There's a version for making web apps too. Spring aims to make Java EE easy and to help programmers do good work.

What can you do with Spring?

  • Use Simple Objects: With Spring, you use simple objects called POJOs to make big apps. This means you don't need heavy tools; just use simple ones like Tomcat.

  • Pick What You Need: Spring has many parts, but you can just use what you need and forget the rest.

  • Works with Others: Spring uses already made tools, like logging tools, JEE, and timers.

  • Easy to Test: Testing apps made with Spring is easy. You can easily put in test data because of how it's set up.

  • Web Framework: Spring has a good web tool that you can use instead of others like Struts.

  • Handle Errors Well: Spring can change tech-specific errors into general ones.

  • It's Light: Spring tools, especially compared to some like EJB, are light. This is great for devices with not a lot of memory or power.


Spring Tutorial Index


Basics – Java Spring Framework

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Boot

Spring MVC

Spring with REST API

Spring Data

Spring JDBC

Spring ORM or Spring Hibernate

Spring AOP

Spring Security


Basics of Spring Framework


Introduction to Spring Framework

Spring Framework Architecture

10 Reasons to Use Spring Framework in Projects

Spring Initializr

Difference Between Spring DAO vs Spring ORM vs Spring JDBC

Top 10 Most Common Spring Framework Mistakes

Spring vs. Struts in Java


Software Setup and Configuration 


(STS/Eclipse/IntelliJ)

How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?

How to Create and Setup Spring Boot Project in Spring Tool Suite?

How to Create a Spring Boot Project with IntelliJ IDEA?

How to Create and Setup Spring Boot Project in Eclipse IDE?

How to Create a Dynamic Web Project in Eclipse/Spring Tool Suite?

How to Run Your First Spring Boot Application in IntelliJ IDEA?

How to Run Your First Spring Boot Application in Spring Tool Suite?

How to Turn on Code Suggestion in Eclipse or Spring Tool Suite?







Core Spring


Understanding Inversion of Control with Example

Spring – BeanFactory

Spring – ApplicationContext

Spring – Difference Between BeanFactory and ApplicationContext

Spring Dependency Injection with Example

Spring – Difference Between Inversion of Control and Dependency Injection

Spring – Injecting Objects By Constructor Injection

Spring – Setter Injection with Map

Spring – Dependency Injection with Factory Method

Spring – Dependency Injection by Setter Method

Spring – Setter Injection with Non-String Map

Spring – Constructor Injection with Non-String Map

Spring – Constructor Injection with Map

Spring – Setter Injection with Dependent Object

Spring – Constructor Injection with Dependent Object

Spring – Setter Injection with Collection

Spring – Setter Injection with Non-String Collection

Spring – Constructor Injection with Collection

Spring – Injecting Objects by Setter Injection

Spring – Injecting Literal Values By Setter Injection

Spring – Injecting Literal Values By Constructor Injection

Bean life cycle in Java Spring

Custom Bean Scope in Spring

How to Create a Spring Bean in 3 Different Ways?

Spring – IoC Container

Spring – Autowiring

Singleton and Prototype Bean Scopes in Java Spring

How to Configure Dispatcher Servlet in web.xml File?

Spring – Configure Dispatcher Servlet in Three Different Ways

How to Configure Dispatcher Servlet in Just Two Lines of Code in Spring?

Spring – When to Use Factory Design Pattern Instead of Dependency Injection

How to Create a Simple Spring Application?

Spring – init() and destroy() Methods with Example

Spring WebApplicationInitializer with Example

Spring – Project Modules

Spring – Remoting by HTTP Invoker

Spring – Expression Language(SpEL)

Spring – Variable in SpEL

What is Ambiguous Mapping in Spring?

Spring – Add New Query Parameters in GET Call Through Configurations

Spring – Integrate HornetQ

Remoting in Spring Framework

Spring – Application Events

Spring c-namespace with Example

Parse Nested User-Defined Functions using Spring Expression Language (SpEL)

Spring – AbstractRoutingDataSource

Circular Dependencies in Spring

Spring – ResourceLoaderAware with Example

Spring Framework Standalone Collections

How to Create a Project using Spring and Struts 2?

Spring – Perform Update Operation in CRUD

How to Transfer Data in Spring using DTO?

Spring – Resource Bundle Message Source (i18n)

Spring Application Without Any .xml Configuration

Spring – BeanPostProcessor

Spring and JAXB Integration

Spring – Difference Between Dependency Injection and Factory Pattern

Spring – REST Pagination

Spring – Remoting By Burlap

Spring – Remoting By Hessian

Spring with Castor Example

Spring – REST XML Response

Spring – Inheriting Bean

Spring – Change DispatcherServlet Context Configuration File Name

Spring – JMS Integration

Spring – Difference Between RowMapper and ResultSetExtractor

Spring with Xstream

Spring – RowMapper Interface with Example

Spring – util:constant

Spring – Static Factory Method

Spring – FactoryBean

Difference between EJB and Spring



Annotations


Spring Framework Annotations

Spring Core Annotations

Spring Stereotype Annotations

Spring @Bean Annotation with Example

Spring @Controller Annotation with Example

Spring @Value Annotation with Example

Spring @Configuration Annotation with Example

Spring @ComponentScan Annotation with Example

Spring @Qualifier Annotation with Example

Spring @Service Annotation with Example

Spring @Repository Annotation with Example

Spring @Required Annotation

Spring @Component Annotation with Example

Spring @Autowired Annotation

Spring @PostConstruct and @PreDestroy Annotation with Example

Spring @PropertySource Annotation and Resource Interface

Spring @Scope Annotation to Set a POJO’s Scope

Spring @Required Annotation with Example



Spring Boot


Introduction to Spring Boot

Best Way to Master Spring Boot – A Complete Roadmap

How to Create a Spring Boot Project?

How to Create a Spring Boot Project with IntelliJ IDEA?

How to Run Your First Spring Boot Application in Spring Tool Suite?

Spring Boot – Annotations

Spring Boot – Architecture

Spring Boot Actuator

How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?

Spring Boot – Introduction to RESTful Web Services

How to create a basic application in Java Spring Boot

How to create a REST API using Java Spring Boot

Easiest Way to Create REST API using Spring Boot

Java Spring Boot Microservices Sample Project

Difference between Spring MVC and Spring Boot

Spring Boot – Spring JDBC vs Spring Data JDBC

Best Practices For Structuring Spring Boot Application

Spring Boot – Start/Stop a Kafka Listener Dynamically

How to Dockerize a spring boot application with maven

Dynamic Dropdown From Database using Spring Boot

Spring – RestTemplate

Spring Boot – Scheduling

Spring Boot – Sending Email via SMTP

Different Ways to Establish Communication Between Spring Microservices

JSON using Jackson in REST API Implementation with Spring Boot

How to encrypt passwords in a Spring Boot project using Jasypt

Containerizing Java applications | Creating a Spring Boot App using Dockerfile

How to Send Images in Spring Boot without using Servlet and Redundant JSP Codes?

How to Create Todo List API using Spring Boot and MySQL?

Spring Boot – Transaction Management Using @Transactional Annotation

Spring Boot – Map Entity to DTO using ModelMapper

Spring Boot – How to consume JSON messages using Apache Kafka

Spring Boot – How to consume string messages using Apache Kafka

Spring Boot – How to publish String messages on Apache Kafka

Spring Boot – How to publish JSON messages on Apache Kafka

Spring Boot – Consume JSON Object From Kafka Topics

Spring Boot Kafka Producer Example

Spring Boot Kafka Consumer Example

Message Compression in Apache Kafka using Spring Boot

Spring Boot – Create and Configure Topics in Apache Kafka

How to Test Spring Boot Project using ZeroCode?

Validation in Spring Boot

Spring Boot – Validation using Hibernate Validator

How to Connect MongoDB with Spring Boot?

Spring Boot – File Handling

Spring Boot MockMVC Testing with Example Project

Spring Boot Integration With MySQL as a Maven Project

Spring Boot Integration With MongoDB as a Maven Project

Spring Boot MockMVC Example

Spring Boot Integration With PostgreSQL as a Maven Project

Spring Boot JPA Sample Maven Project With Query Methods

Spring Boot – Service Class Example for Displaying Response Codes and Custom Error Codes

Spring Boot – Create a Custom Auto-Configuration

Spring Boot – Consume Message Through Kafka, Save into ElasticSearch, and Plot into Grafana

How to Implement AOP in Spring Boot Application?

Spring Boot – AOP(Aspect Oriented Programming)

Spring Boot – Cache Provider

Spring Boot – AOP Around Advice

Spring Boot – Auto-configuration

Spring Boot – EhCaching

Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat

Spring Boot Actuator

Spring Boot – Starter Test

Spring Boot – Exception Handling

Spring Boot – Project Deployment Using Tomcat

Spring Boot – Difference Between AOP and OOP

Spring Boot – Difference Between AOP and AspectJ

Spring Boot – Logging

Advantages of Spring Boot JDBC

Spring Boot – Packaging

Spring Boot – JDBC

Spring Boot – AOP After Throwing Advice

Spring Boot – AOP After Returning Advice

Spring Boot – Multi-Module Project

Spring Boot – AOP After Advice

Spring Boot – AOP Before Advice

Spring Boot – DevTools

Spring Boot – Dependency Management

Spring Boot – Caching

Spring Boot – Starter Web

Spring Boot – Difference Between @Service Annotation and @Repository Annotation

Unit Testing in Spring Boot Project using Mockito and Junit

Spring Boot – Thymeleaf with Example

Spring Boot – MongoRepository with Example

Spring Boot – Integrating Hibernate and JPA

Spring Boot JpaRepository with Example

Spring Boot – CRUD Operations using MongoDB

Spring Boot – Spring Data JPA

Upload Multiple Files in Spring Boot using JPA, Thymeleaf, Multipart

Spring Boot – Difference Between CrudRepository and JpaRepository

Spring Boot – CrudRepository with Example

Spring Boot – application.yml/application.yaml File

Spring Boot – CRUD Operations using MySQL Database

How to Implement One to Many Mapping in Spring Boot?

How to Run Your First Spring Boot Application in Eclipse IDE?

How to Run Spring Boot Application?

Spring Boot – Application Properties

Spring Boot – H2 Database

Spring Boot – CRUD Operations

Spring Boot – REST Example

How to Run Your First Spring Boot Application in IntelliJ IDEA?

Spring Boot – Change Port

Spring Boot – Hello World Example

What is Command Line Runner Interface in Spring Boot?

How to Create and Setup Spring Boot Project in Eclipse IDE?

How to Create and Setup Spring Boot Project in Spring Tool Suite?

How to Make a Simple RestController in Spring Boot?

How to Implement Simple Authentication in Spring Boot?

What is PathVariable in the Spring Boot?

How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA?

How to Get the Body of Request in Spring Boot?

How to Make Put Request in Spring Boot?

Deploying Spring Boot Application with MySQL Database on Azure

How to Call or Consume External API in Spring Boot?

Spring Boot – Starter Parent

Spring Boot – Customize the Jackson ObjectMapper

Spring Boot – Starters

Spring Boot – Code Structure


Spring MVC



Introduction to Spring MVC

Spring MVC using Java-based configuration

ViewResolver in Spring MVC

How to Create Your First Model in Spring MVC?

How to Create Your First View in Spring MVC?

Spring MVC CRUD with Example

Create and Run Your First Spring MVC Controller in Eclipse/Spring Tool Suite

What is Dispatcher Servlet in Spring?

Spring – Shortcut to Create Dispatcher Servlet in Eclipse/Spring Tool Suite

WebApplicationContext in Spring MVC

Spring – Multi Action Controller with Example

Spring MVC – Exception Handling

Spring – How to Load Literal Values From Properties File

Spring MVC – Multiple View Page

Spring MVC – Custom Validation

Difference Between ApplicationContext and WebApplicationContext in Spring MVC

Difference Between @Component, @Repository, @Service, and @Controller Annotations in Spring

Difference Between @Controller and @Service Annotation in Spring

Difference Between @Controller and @RestController Annotation in Spring

Spring MVC – RequestParam Annotation

Query String and Query Parameter in Spring MVC

How to Make Post Request in Java Spring?

How to Make Delete Request in Spring?

How to Make get() Method Request in Java Spring?

Spring @RequestMapping Annotation with Example

How to Capture Data using @RequestParam Annotation in Spring?

Spring @ResponseBody Annotation with Example

Spring MVC Project – Retrieving Population, Area and Region Details using Rest API

Spring MVC – Last 24-Hour Cryptocurrency Data using REST API

Spring MVC – Sample Project For Finding Doctors Online with MySQL

Spring MVC JSTL Configuration

Spring MVC with MySQL – Sample Project For Calculating Electricity Bill

Spring MVC – Comparison of Cryptocurrencies using REST API

Spring MVC – Get Probability of a Gender by Providing a Name using REST API

Get Time Zone by Providing Latitude and Longitude using Spring MVC and REST API

Spring MVC with MySQL and Junit – Finding Employees Based on Location

Spring MVC – Get University/College Details via REST API

Spring MVC – JSTL forEach Tag with Example

Spring MVC – Iterating List on JSP using JSTL

Two-Way Data Binding in Spring MVC with Example

Spring MVC – Basic Example using JSTL

Spring MVC @ModelAttribute Annotation with Example

Data Transfer Object (DTO) in Spring MVC with Example

Spring MVC – Capture and Display the Data from Registration Form

Spring MVC – Create Registration Form using Form Tag Library

Data Binding in Spring MVC with Example

Spring MVC – Pagination with Example

Spring MVC Integration with MySQL

OpenSource REST API URL and Retrieving Data From it By Using Spring MVC

How to Resolve WEB xml is missing and failOnMissingWebXml is set to true in Eclipse/STS?

Spring MVC Application Without web.xml File

Spring MVC – Listbox

Spring MVC – Multiple Resolver Mapping

How to Extract TV Show Details via REST API and Spring MVC?

Spring MVC File Upload

Spring MVC – Tiles

Spring MVC – Text Box

Spring MVC – Multiple Controller

Spring MVC – Model Interface

Spring MVC – Number Validation

Spring MVC – Form Checkbox

Spring MVC – Form Radio Button

Spring MVC – Form Drop-Down List

Spring MVC – TextArea

Spring MVC – Hidden Field

Spring MVC – Regular Expression Validation

Spring MVC – Password

Spring MVC – Form Tag Library

Spring MVC – Form Text Field

Spring MVC – Validation

Spring MVC – Form Handling

How to Create a Project using Spring MVC and Hibernate 5?

Spring MVC – Getting Cryptocurrency Details using REST API

Spring MVC – Get Exchange Rate Values using REST API


Spring with REST API



Spring REST JSON Response

Spring – REST XML Response

Spring – REST Controller

Spring MVC – Getting Cryptocurrency Details using REST API

Spring MVC – Get Exchange Rate Values using REST API

Spring Boot – Introduction to RESTful Web Services

How to create a REST API using Java Spring Boot

Easiest Way to Create REST API using Spring Boot

JSON using Jackson in REST API Implementation with Spring Boot

How to Make a Simple RestController in Spring Boot?

Spring MVC Project – Retrieving Population, Area and Region Details using Rest API

Spring MVC – Last 24 Hour Cryptocurrency Data using REST API

Spring MVC – Comparison of Cryptocurrencies using REST API

Spring MVC – Get Probability of a Gender by Providing a Name using REST API

Get Time Zone by Providing Latitude and Longitude using Spring MVC and REST API

Spring MVC – Get University/College Details via REST API

OpenSource REST API URL and Retrieving Data From it By Using Spring MVC

How to Extract TV Show Details via REST API and Spring MVC?

Spring MVC – Getting Cryptocurrency Details using REST API

Spring MVC – Get Exchange Rate Values using REST API

Spring Boot – Introduction to RESTful Web Services

How to create a basic application in Java Spring Boot

How to create a REST API using Java Spring Boot

Easiest Way to Create REST API using Spring Boot

Spring – RestTemplate

JSON using Jackson in REST API Implementation with Spring Boot

Spring Boot – REST Example

How to Make a Simple RestController in Spring Boot?

Difference Between @Controller and @RestController Annotation in Spring

Spring MVC Project – Retrieving Population, Area and Region Details using Rest API

Spring MVC – Last 24 Hour Cryptocurrency Data using REST API

Spring MVC – Comparison of Cryptocurrencies using REST API

Spring MVC – Get Probability of a Gender by Providing a Name using REST API

Get Time Zone by Providing Latitude and Longitude using Spring MVC and REST API

Spring MVC – Get University/College Details via REST API

OpenSource REST API URL and Retrieving Data From it By Using Spring MVC

How to Extract TV Show Details via REST API and Spring MVC?

Spring MVC – Getting Cryptocurrency Details using REST API

Spring MVC – Get Exchange Rate Values using REST API


Spring Data


What is Spring Data JPA?

JPA vs Hibernate

Spring Data JPA – Find Records From MySQL

Spring Data JPA – Delete Records From MySQL

Spring Data JPA – @Table Annotation

Spring Data JPA – Insert Data in MySQL Table

Spring Data JPA – Attributes of @Column Annotation with Example

Spring Data JPA – @Column Annotation

Spring Data JPA – @Id Annotation

Introduction to the Spring Data Framework

How to access database using Spring Data JPA

How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?

Spring Boot – Integrating Hibernate and JPA

Spring Boot JpaRepository with Example

Spring Boot – Spring Data JPA


Spring JDBC


Spring JDBC Template

Spring JDBC Example

Spring – SimpleJDBCTemplate with Example

Spring – Prepared Statement JDBC Template

Spring – NamedParameterJdbcTemplate

Spring – Using SQL Scripts with Spring JDBC + JPA + HSQLDB

Spring – ResultSetExtractor


Spring ORM or Spring Hibernate


Spring Hibernate Configuration and Create a Table in the Database

Hibernate Lifecycle

JPA vs Hibernate

Spring ORM Example using Hibernate

Spring Boot – Validation using Hibernate Validator

How to Create a Project Using Spring MVC and Hibernate 5?

Hibernate – One-to-One Mapping

Spring Boot – Integrating Hibernate and JPA

Hibernate – Cache Eviction with Example

Hibernate – Cache Expiration

Hibernate – Enable and Implement First and Second Level Cache

Hibernate – Save Images and Other Types of Values to the Database

Hibernate – Pagination

Hibernate – Different Cascade Types

Hibernate Native SQL Query with Example

Hibernate – Caching

Hibernate – @Embeddable and @Embedded Annotation

Hibernate – Eager/Lazy Loading

Hibernate – get() and load() Method

Hibernate Validator with Example

CRUD Operations using Hibernate

Hibernate Example without IDE

Hibernate – Inheritance Mapping

Automatic Table Creation Using Hibernate

Hibernate – Batch Processing

Hibernate – Component Mapping

Hibernate – Mapping List

Hibernate – Collection Mapping

Hibernate – Bag Mapping

Hibernate – Difference Between List and Bag Mapping

Hibernate – SortedSet Mapping

Hibernate – SortedMap Mapping

Hibernate – Native SQL

Hibernate – Logging by Log4j using XML File

Hibernate – Many-to-One Mapping

Hibernate – Logging By Log4j Using Properties File

Hibernate – Table Per Concrete Class Using Annotation

Hibernate – Table Per Subclass using Annotation

Hibernate – Interceptors

Hibernate – Many-to-Many Mapping

Hibernate – Types of Mapping

Hibernate – Criteria Queries

Hibernate – Table Per Hierarchy using Annotation

Hibernate – Table Per Subclass Example using XML File

Hibernate – Table Per Hierarchy using XML File

Hibernate – Create POJO Classes

Hibernate – Web Application

Hibernate – Table Per Concrete Class using XML File

Hibernate – Generator Classes

Hibernate – SQL Dialects

Hibernate – Query Language

Hibernate – Difference Between ORM and JDBC

Hibernate – Annotations

Hibernate Example using XML in Eclipse

Hibernate – Create Hibernate Configuration File with the Help of Plugin

Hibernate Example using JPA and MySQL

Hibernate – One-to-Many Mapping


Spring AOP


Aspect-Oriented Programming and AOP in Spring Framework

Spring Boot – AOP Around Advice

Spring Boot – AOP(Aspect Oriented Programming)

How to Implement AOP in Spring Boot Application?

Spring AOP – Example (Spring1.2 Old Style AOP)

Spring AOP – AspectJ Xml Configuration

Spring AOP – AspectJ Annotation

Usage of @Before, @After, @Around, @AfterReturning, and @AfterThrowing in a Single Spring AOP Project

How to Implement AOP in Spring Boot Application?

Spring Boot – AOP(Aspect Oriented Programming)

Spring Boot – Cache Provider

Spring Boot – AOP Around Advice

Spring Boot – Difference Between AOP and OOP

Spring Boot – Difference Between AOP and AspectJ

Spring Boot – AOP After Throwing Advice

Spring Boot – AOP After Returning Advice

Spring Boot – AOP After Advice

Spring Boot – AOP Before Advice


Spring Security

Introduction to Spring Security and its Features

Some Important Terms in Spring Security

OAuth2 Authentication with Spring and Github

Spring Security at Method Level

Spring Security JSP Tag Library

Spring Security Form-Based Authentication

Spring Security – Remember Me

Spring Security XML

Spring Security Project Example using Java Configuration

How to Change Default User and Password in Spring Security?

Spring – Add Roles in Spring Security

Spring – Add User Name and Password in Spring Security


Advantages of Spring


Predefined Templates

Loose Coupling

Lightweight

Fast Development

Powerful abstraction

Declarative support






Spring Tutorial Index



Topic

Description of Topic

Basics – Java Spring Framework

- Foundation of the Spring ecosystem


- Provides a comprehensive programming and configuration model for Java applications

Software Setup and Configuration

- Setting up the development environment using tools like STS, Eclipse, or IntelliJ


- Ensures smooth development and execution of Spring applications

Core Spring

- Central part of the Spring Framework


- Provides core functionalities like Dependency Injection and Aspect-Oriented Programming

Spring Boot

- Extension of the Spring Framework to simplify its setup and usage


- Offers production-ready applications quickly with minimal configurations

Spring MVC

- Framework to build web applications following the Model-View-Controller pattern


- Handles web requests and responses efficiently

Spring with REST API

- Enables the development of RESTful web services


- Integrates HTTP methods to provide CRUD operations through APIs

Spring Data

- Streamlines data access operations from various data sources


- Provides a consistent data access layer using repositories

Spring JDBC

- Facilitates database operations using Java Database Connectivity


- Minimizes boilerplate code and streamlines error handling

Spring ORM or Spring Hibernate

- Provides integration with Object-Relational Mapping tools, especially Hibernate


- Bridges the gap between Java objects and relational databases

Spring AOP

- Aspect-Oriented Programming in Spring to handle cross-cutting concerns


- Modularizes the application to separate concerns like logging and transactions from business logic

Spring Security

- Comprehensive framework for authentication and authorization


- Offers protection against common vulnerabilities and integrates seamlessly with other Spring modules


Basics of Spring Framework



Topic

Topic Content

Introduction to Spring Framework

- A Java framework for enterprise applications.


- Provides dependency injection, AOP, data access, and more.

Spring Framework Architecture

- Modular design with various projects/modules like Spring Boot, Spring Data, etc.


- Key components include Core Container, AOP, Data Access/Integration, Web MVC, and Security.

10 Reasons to Use Spring Framework in Projects

- Dependency Injection support.


- AOP for cross-cutting concerns.


- Robust data access using JDBC and ORM.


- Comprehensive MVC framework.


- Modularity and a wide range of extensions.


- (and more reasons as per the full notes)

Spring Initializr

- Web tool to start new Spring projects.


- Generates project structure and default configurations.

Difference Between Spring DAO vs Spring ORM vs Spring JDBC

- DAO: Data Access Object, a design pattern for data access.


- ORM: Object-Relational Mapping, integration with frameworks like Hibernate.


- JDBC: Direct database operations using Java Database Connectivity.

Top 10 Most Common Spring Framework Mistakes

- Not using the Spring's latest version.


- Incorrect bean configuration.


- Not utilizing Spring's security features.


- Mixing XML and annotation configurations without understanding.


- (and more mistakes as per the full notes)

Spring vs. Struts in Java

- Spring: Comprehensive framework, provides tools for both backend and frontend, more than just web applications.


- Struts: A specific web framework focusing on the web layer using MVC pattern.

Software Setup and Configuration 



Topic

Topic Content

How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?

- Visit the official Spring website.


- Choose the appropriate version for your OS.


- Download and initiate installation.


- Follow on-screen prompts to complete installation.

How to Create and Setup Spring Boot Project in Spring Tool Suite?

- Open Spring Tool Suite.


- Navigate to File > New > Spring Starter Project.


- Input project details and choose necessary dependencies.


- Finish project creation wizard.

How to Create a Spring Boot Project with IntelliJ IDEA?

- Start IntelliJ IDEA.


- Choose File > New > Project... > Spring Initializr.


- Configure project metadata and select dependencies.


- Click Finish to generate the project.

How to Create and Setup Spring Boot Project in Eclipse IDE?

- Start Eclipse.


- Ensure you have the Spring Boot plugins installed.


- Go to File > New > Spring Starter Project.


- Input project details, choose dependencies, and finalize.

How to Create a Dynamic Web Project in Eclipse/Spring Tool Suite?

- Open Eclipse or Spring Tool Suite.


- Select File > New > Dynamic Web Project.


- Input project name and other details, then click Finish.

How to Run Your First Spring Boot Application in IntelliJ IDEA?

- Open the project in IntelliJ.


- Locate the main application class in the project explorer.


- Right-click and select Run 'ClassName.main()'.

How to Run Your First Spring Boot Application in Spring Tool Suite?

- Navigate to the Boot Dashboard.


- Right-click on your project and select Run As > Spring Boot App.

How to Turn on Code Suggestion in Eclipse or Spring Tool Suite?

- Navigate to Window > Preferences.


- Go to Java > Editor > Content Assist and ensure 'Enable auto activation' is checked.

Core Spring





Topic

Topic Content/Answer

JAVA Code Example

Understanding Inversion of Control with Example

- Inversion of Control (IoC) refers to the transfer of object creation and its dependencies to a container or framework.

ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

Spring – BeanFactory

- BeanFactory is the core container providing basic IoC capabilities.

BeanFactory factory = new XmlBeanFactory(new ClassPathResource("Beans.xml"));

Spring – ApplicationContext

- ApplicationContext offers advanced container functionalities, event propagation, and more.

ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

Difference Between BeanFactory and ApplicationContext

- ApplicationContext is a superset of BeanFactory.

N/A


- ApplicationContext provides additional features like event propagation and easier integration with AOP.


Spring Dependency Injection with Example

- Process of providing dependencies of an object from outside.

@Autowired private SomeClass someObject;

Difference Between IoC and Dependency Injection

- IoC is a design principle, DI is a pattern to implement IoC.

N/A

Spring – Injecting Objects By Constructor Injection

- Provide dependencies via constructor.

public ClassName(DependencyClass dependency){...}

Spring – Setter Injection with Map

- Inject values into a Map property via setters.

public void setMapProperty(Map<String, Object> map){...}

Spring – Dependency Injection with Factory Method

- Use a static method to return an instance of the bean.

public static ClassName createInstance() {...}

Spring – Dependency Injection by Setter Method

- Provide dependencies via setter methods.

public void setDependency(DependencyClass dependency){...}

Spring – Setter Injection with Non-String Map

- Inject non-string key-value pairs into a Map property.

public void setMapProperty(Map<Object, Object> map){...}

Spring – Constructor Injection with Non-String Map

- Provide non-string Map dependencies via constructor.

public ClassName(Map<Object, Object> map){...}

Spring – Constructor Injection with Map

- Provide Map dependencies via constructor.

public ClassName(Map<String, Object> map){...}

Spring – Setter Injection with Dependent Object

- Inject a dependent object via setter method.

public void setDependentObj(DependentClass obj){...}

Spring – Constructor Injection with Dependent Object

- Provide dependent object as a dependency via constructor.

public ClassName(DependentClass obj){...}

Spring – Setter Injection with Collection

- Inject a Collection (List, Set, etc.) via setter.

public void setListProperty(List<Object> list){...}

Spring – Setter Injection with Non-String Collection

- Inject a Collection of non-string objects via setter.

public void setListProperty(List<Object> list){...}

Spring – Constructor Injection with Collection

- Provide a Collection (List, Set, etc.) as a dependency via constructor.

public ClassName(List<Object> list){...}



Topic

Topic Content/Answer

JAVA Code Example

Spring – Injecting Objects by Setter Injection

- Injecting dependencies using setter methods.

public void setSomeClass(SomeClass someClass){...}

Spring – Injecting Literal Values By Setter Injection

- Injecting simple values like int, string via setter methods.

public void setAge(int age){...}

Spring – Injecting Literal Values By Constructor Injection

- Injecting simple values through constructor.

public ClassName(String name, int age){...}

Bean life cycle in Java Spring

- Lifecycle of a Spring bean from creation to destruction.

@PostConstruct & @PreDestroy

Custom Bean Scope in Spring

- Custom bean scopes apart from the standard singleton & prototype.

@Scope("custom")

How to Create a Spring Bean in 3 Different Ways?

- Using XML, annotations, and Java config.

@Component, XML <bean>, Java @Configuration

Spring – IoC Container

- Responsible for managing the lifecycle & configuration of Spring beans.

ApplicationContext ctx = ...

Spring – Autowiring

- Automatically wiring bean dependencies without explicit wiring.

@Autowired

Singleton and Prototype Bean Scopes in Java Spring

- Singleton: one instance; Prototype: new instance every time.

@Scope("singleton"), @Scope("prototype")

How to Configure Dispatcher Servlet in web.xml File?

- Configuring central dispatcher for Spring MVC in web.xml.

<servlet>, <servlet-mapping>

Spring – Configure Dispatcher Servlet in Three Different Ways

- Using XML, Java config, and Servlet 3.0 initialization.

WebApplicationInitializer, XML <servlet>, etc.

How to Configure Dispatcher Servlet in Just Two Lines of Code in Spring?

- Simplified configuration for dispatcher servlet.

ServletRegistration.Dynamic dispatcher = ...

Spring – When to Use Factory Design Pattern Instead of Dependency Injection

- Factory pattern for complex creation; DI for simpler and managed instantiation.

new FactoryClass().createInstance()

How to Create a Simple Spring Application?

- Basic steps to set up a minimal Spring application.

ApplicationContext ctx = ...

Spring – init() and destroy() Methods with Example

- Callback methods invoked on bean initialization & destruction.

@PostConstruct, @PreDestroy

Spring WebApplicationInitializer with Example

- Interface for programmatic registration of servlets, filters, etc.

public class MyAppInitializer implements WebApplicationInitializer{...}


Topic

Topic Content/Answer

JAVA Code Example

Spring – Project Modules

- Organized parts of a Spring application for easier management.

@Module or Maven <module> tag in pom.xml

Spring – Remoting by HTTP Invoker

- A technique to expose Spring beans over HTTP.

HttpInvokerServiceExporter, HttpInvokerProxyFactoryBean

Spring – Expression Language(SpEL)

- A powerful expression language for querying/manipulating objects at runtime.

@Value("#{beanName.property}")

Spring – Variable in SpEL

- Dynamic values in SpEL expressions.

@Value("#{${dynamic.value}}")

What is Ambiguous Mapping in Spring?

- Occurs when more than one method matches a particular request URL pattern in Spring MVC.

@RequestMapping("/sameURL") in multiple methods

Spring – Add New Query Parameters in GET Call Through Configurations

- Dynamically adding query params to GET requests through Spring configuration.

N/A (specific configuration code might be needed)

Spring – Integrate HornetQ

- Integration of HornetQ messaging system with Spring for asynchronous processing.

JmsTemplate, HornetQJMSConnectionFactory

Remoting in Spring Framework

- Exposing Spring beans as remote services.

RmiServiceExporter, JaxWsPortProxyFactoryBean

Spring – Application Events

- Custom events that can be published and listened to within a Spring application.

ApplicationEventPublisher.publishEvent(myEvent);

Spring c-namespace with Example

- A way to simplify Spring XML configurations using constructor injection.

<bean class="MyClass" c:_0-ref="anotherBean" c:_1="someValue"/>


Topic

Topic Content/Answer

JAVA Code Example

Parse Nested User-Defined Functions using Spring Expression Language (SpEL)

- Parsing custom methods within SpEL.

@Value("#{myBean.myMethod('arg')}")

Spring – AbstractRoutingDataSource

- Route a data source based on a lookup key. Useful in multi-database scenarios.

public class MyRoutingDataSource extends AbstractRoutingDataSource { ... }

Circular Dependencies in Spring

- Issue when two or more beans depend on each other, causing a cyclic dependency.

N/A (but can be illustrated with bean diagrams)

Spring – ResourceLoaderAware with Example

- Interface for beans that need access to resource loading.

public class MyResourceLoader implements ResourceLoaderAware { ... }

Spring Framework Standalone Collections

- Defining and using collections (List, Set, Map, etc.) within Spring.

<list><value>Value1</value></list>

How to Create a Project using Spring and Struts 2?

- Integrating Spring with Struts 2 to benefit from both frameworks.

N/A (project setup code, but might involve XML or annotations)

Spring – Perform Update Operation in CRUD

- Using Spring to perform an update operation in CRUD functionalities.

jdbcTemplate.update(UPDATE_SQL, params);

How to Transfer Data in Spring using DTO?

- Data Transfer Objects (DTO) help in transferring data between layers and modules.

public class UserDTO { private String name; ... }

Spring – Resource Bundle Message Source (i18n)

- Internationalization support in Spring using resource bundles.

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">

Spring Application Without Any .xml Configuration

- Building Spring applications using only Java-based configuration, without XML.

@Configuration, @Bean

Spring – BeanPostProcessor

- Allows for custom modification of new bean instances, e.g., checking or proxying.

public class MyBeanPostProcessor implements BeanPostProcessor { ... }

Spring and JAXB Integration

- Integrating Java Architecture for XML Binding (JAXB) with Spring for XML marshalling/unmarshalling.

Jaxb2Marshaller marshaller = new Jaxb


Here are the table-liked flashcards based on your Spring topics notes:

Topic

Topic Content/Answer

JAVA Code Example

Spring – Difference Between Dependency Injection and Factory Pattern

- DI: injecting dependencies through constructor or setters. Factory: creating objects without exposing creation logic.

N/A

Spring – REST Pagination

- Handling large datasets by dividing them into smaller chunks/pages.

PageRequest page = PageRequest.of(pageNumber, pageSize);

Spring – Remoting By Burlap

- Using Burlap for remote communication in Spring.

BurlapProxyFactoryBean proxy = new BurlapProxyFactoryBean();

Spring – Remoting By Hessian

- Using Hessian for efficient binary remoting in Spring.

HessianProxyFactoryBean proxy = new HessianProxyFactoryBean();

Spring with Castor Example

- Marshalling/unmarshalling XML using Castor library in Spring.

N/A (This involves the Castor library and XML configurations)

Spring – REST XML Response

- Generating XML responses for RESTful web services in Spring.

@RequestMapping(produces = "application/xml")

Spring – Inheriting Bean

- Bean inheritance to reuse configurations and properties.

<bean id="childBean" parent="parentBean">

Spring – Change DispatcherServlet Context Configuration File Name

- Customizing the configuration filename of DispatcherServlet.

DispatcherServlet servlet = new DispatcherServlet(); servlet.setContextConfigLocation("myConfig.xml");

Spring – JMS Integration

- Integrating Java Message Service (JMS) with Spring for messaging.

JmsTemplate jmsTemplate = new JmsTemplate();

Spring – Difference Between RowMapper and ResultSetExtractor

- RowMapper: map one row. ResultSetExtractor: process entire ResultSet.

N/A

Spring with Xstream

- Using Xstream for XML serialization/deserialization within Spring.

N/A (This involves the Xstream library)

Spring – RowMapper Interface with Example

- An interface used to map rows on a per-row basis.

public class UserRowMapper implements RowMapper<User> { ... }

Spring – util:constant

- Accessing static constants in Spring configuration.

<util:constant static-field="com.example.MyClass.MY_CONSTANT"/>

Spring – Static Factory Method

- A method that returns an instance of its class.

public static MyBean getInstance() { return new MyBean(); }

Spring – FactoryBean

- A factory pattern adaptation in Spring for creating beans.

public class MyFactoryBean implements FactoryBean<MyBean> { ... }

Difference between EJB and Spring

- EJB: Java EE component for building distributed apps. Spring: Comprehensive framework with DI, AOP, etc.

N/A


Annotations



Topic

Topic Content/Answer

JAVA Code Example

Spring Framework Annotations

- Annotations provided by Spring to simplify configuration and behavior.

N/A

Spring Core Annotations

- Basic annotations for core Spring functionalities.

@Bean, @Autowired, @Value, ...

Spring Stereotype Annotations

- Annotations to indicate the role of a type or method.

@Controller, @Service, @Repository, @Component

Spring @Bean Annotation with Example

- Defines a bean to be managed by Spring.

@Bean public MyBean myBean() { return new MyBean(); }

Spring @Controller Annotation with Example

- Indicates that the class is a web controller.

@Controller public class MyController { ... }

Spring @Value Annotation with Example

- Indicates a default value expression for the affected argument or field.

@Value("${property.name}") private String name;

Spring @Configuration Annotation with Example

- Indicates that the class can be used by Spring as a source of bean definitions.

@Configuration public class AppConfig { ... }

Spring @ComponentScan Annotation with Example

- Configures component scanning directives for use with @Configuration classes.

@ComponentScan("com.example.package")

Spring @Qualifier Annotation with Example

- Indicates which exact bean should be wired, when multiple beans of the same type exist.

@Autowired @Qualifier("specificBeanName") private MyBean myBean;

Spring @Service Annotation with Example

- Indicates that the class is a service component.

@Service public class MyService { ... }

Spring @Repository Annotation with Example

- Indicates that the class is a repository.

@Repository public class MyRepository { ... }

Spring @Required Annotation

- Indicates that the affected bean property must be populated at configuration time.

@Required public void setBean(MyBean bean) { ... }

Spring @Component Annotation with Example

- Generic stereotype for any Spring-managed component.

@Component public class MyComponent { ... }

Spring @Autowired Annotation

- Marks a method, constructor, field, or config method parameter as to be autowired by Spring's dependency injection facilities.

@Autowired private MyBean myBean;

Spring @PostConstruct and @PreDestroy Annotation with Example

- @PostConstruct: after bean initialization. @PreDestroy: before bean destruction.

@PostConstruct public void init() { ... } @PreDestroy public void destroy() { ... }

Spring @PropertySource Annotation and Resource Interface

- Provides a convenient way to add property sources to the environment.

@PropertySource("classpath:config.properties")

Spring @Scope Annotation to Set a POJO’s Scope

- Defines the scope of a bean, such as singleton or prototype.

@Scope("prototype")

Spring @Required Annotation with Example

- Indicates that the bean must be wired at configuration time.

@Required public void setBean(MyBean bean) { ... }

Spring Boot



Topic

Topic Content/Answer

JAVA Code Example

Introduction to Spring Boot

- Introduction to the Spring Boot framework which simplifies Spring application bootstrapping and development.

N/A

Best Way to Master Spring Boot – A Complete Roadmap

- A comprehensive guide or path to becoming proficient in Spring Boot.

N/A

How to Create a Spring Boot Project?

- Steps to set up a new Spring Boot project using the Spring Initializr or other tools.

N/A

How to Create a Spring Boot Project with IntelliJ IDEA?

- Instructions to set up a Spring Boot project specifically using the IntelliJ IDEA IDE.

File -> New -> Project -> Spring Initializr

How to Run Your First Spring Boot Application in Spring Tool Suite?

- Guideline on how to run a Spring Boot application in the Spring Tool Suite IDE.

Right click on project -> Run As -> Spring Boot App

Spring Boot – Annotations

- A review of various annotations provided by Spring Boot for configuration, component scanning, and other tasks.

@SpringBootApplication, @RestController, ...

Spring Boot – Architecture

- An overview of the underlying architecture of Spring Boot, including its conventions and configurations.

N/A

Spring Boot Actuator

- Provides production-ready features to monitor and manage Spring Boot applications, like health checks and environment information.

spring-boot-starter-actuator in pom.xml


Topic

Topic Content/Answer

JAVA Code Example

How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?

- Steps to set up a project combining these technologies. <br>- Setting up Maven dependencies.<br>- Configuration settings for MySQL and JPA.

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>

Spring Boot – Introduction to RESTful Web Services

- Basics of RESTful web services in Spring Boot. <br>- Annotations and conventions used.

@RestController public class MyController { @GetMapping("/hello") public String hello() { return "Hello, World!"; } }

How to create a basic application in Java Spring Boot

- Steps to create a simple Spring Boot application. <br>- Bootstrapping, defining main class and controller.

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

How to create a REST API using Java Spring Boot

- Creating controller classes. <br>- Defining request mappings and response formats.

@RestController public class ApiController { @GetMapping("/data") public Data getData() { return new Data("Sample"); } }

Easiest Way to Create REST API using Spring Boot

- Using Spring Initializr. <br>- Quick setup with default configurations.

@RestController @RequestMapping("/api") public class QuickController { @GetMapping public String quick() { return "Quick API"; } }

Java Spring Boot Microservices Sample Project

- An example project structure for microservices. <br>- Setting up inter-service communication and service discovery.

@SpringBootApplication public class ServiceA { ... }

Difference between Spring MVC and Spring Boot

- Spring MVC is a framework for building web apps, Spring Boot simplifies Spring app bootstrapping. <br>- Boot provides auto-configurations.

N/A

Spring Boot – Spring JDBC vs Spring Data JDBC

- Spring JDBC provides low-level database access, Spring Data JDBC simplifies CRUD operations. <br>- Data JDBC supports repositories.

// Spring JDBC: JdbcTemplate template; template.query(...); // Spring Data JDBC: interface MyRepo extends CrudRepository<MyEntity, Long> {



Topic

Topic Content/Answer

JAVA Code Example

Best Practices For Structuring Spring Boot Application

- Follow the standard directory structure. <br>- Separate concerns using packages. <br>- Use naming conventions consistently.

src/main/java/com/example/demo/controller/ UserController.java

Spring Boot – Start/Stop a Kafka Listener Dynamically

- Use @KafkaListener annotation. <br>- Control with KafkaListenerEndpointRegistry.

@Autowired private KafkaListenerEndpointRegistry registry; ... registry.getListenerContainer("listenerId").stop();

How to Dockerize a spring boot application with maven

- Use the dockerfile-maven-plugin. <br>- Define a Dockerfile.

FROM openjdk:8-jdk-alpine ...

Dynamic Dropdown From Database using Spring Boot

- Use Spring Data JPA. <br>- Fetch entities and transform to DTOs for the dropdown.

@RestController @RequestMapping("/dropdown") public List<DropdownDto> getDropdownOptions() { ... }

Spring – RestTemplate

- Used for consuming RESTful services. <br>- Supports synchronous HTTP requests.

RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

Spring Boot – Scheduling

- Schedule tasks using @Scheduled. <br>- Enable scheduling with @EnableScheduling.

@Scheduled(fixedRate = 1000) public void performTask() { ... }

Spring Boot – Sending Email via SMTP

- Configure SMTP properties. <br>- Use JavaMailSender to send emails.

@Autowired private JavaMailSender emailSender; ... SimpleMailMessage message = new SimpleMailMessage(); ...

Different Ways to Establish Communication Between Spring Microservices

- Use RestTemplate. <br>- Use Feign client. <br>- Employ Spring Cloud Gateway.

@FeignClient(name="service-name") public interface ServiceClient { ... }

JSON using Jackson in REST API Implementation with Spring Boot

- Auto-serialization/deserialization. <br>- Customizing with @JsonProperty and other annotations.

public class User { @JsonProperty("first_name") private String firstName; ... }

How to encrypt passwords in a Spring Boot project using Jasypt

- Use Jasypt for encryption. <br>- Define an encryption password and algorithm.

BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); textEncryptor.setPassword(myPassword);

Containerizing Java applications

Creating a Spring Boot App using Dockerfile

- Write a Dockerfile. <br>- Use commands to set up the Java environment and copy the Spring Boot JAR.

How to Send Images in Spring Boot without using Servlet and Redundant JSP Codes?

- Use ResponseEntity with ByteArrayResource. <br>- Return image as a byte array.

@GetMapping("/image") public ResponseEntity<ByteArrayResource> getImage() { ... }

How to Create Todo List API using Spring Boot and MySQL

- Set up Spring Data JPA with MySQL. <br>- Create CRUD endpoints for Todo items.

@Entity public class Todo { ... } @Repository public interface TodoRepository extends JpaRepository<Todo, Long> { ...




Topic

Topic Content/Answer

JAVA Code Example

Spring Boot – File Handling

- Handle file uploads and downloads. <br>- Use MultipartFile.

@PostMapping("/upload") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {...}

Spring Boot MockMVC Testing with Example Project

- Test MVC layer using MockMvc. <br>- Use mockMvc.perform() method.

MockMvc mockMvc = standaloneSetup(controller).build(); mockMvc.perform(get("/endpoint")).andExpect(status().isOk());

Spring Boot Integration With MySQL as a Maven Project

- Use spring-boot-starter-data-jpa. <br>- Configure MySQL datasource properties.

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>

Spring Boot Integration With MongoDB as a Maven Project

- Use spring-boot-starter-data-mongodb. <br>- Set MongoDB properties.

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>

Spring Boot MockMVC Example

- Test web layer. <br>- Use MockMvc for mock HTTP requests.

mockMvc.perform(MockMvcRequestBuilders.get("/")).andExpect(MockMvcResultMatchers.status().isOk());

Spring Boot Integration With PostgreSQL as a Maven Project

- Use spring-boot-starter-data-jpa. <br>- Configure PostgreSQL datasource properties.

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>

Spring Boot JPA Sample Maven Project With Query Methods

- Define JPA repositories. <br>- Use method naming convention for queries.

public interface UserRepository extends JpaRepository<User, Long> { List<User> findByName(String name); }

Spring Boot – Service Class Example for Displaying Response Codes and Custom Error Codes

- Handle responses in service. <br>- Use custom exceptions for specific error codes.

public ResponseEntity<?> getServiceResponse() { if(error) throw new CustomException("Error occurred"); return ...; }

Spring Boot – Create a Custom Auto-Configuration

- Define custom properties. <br>- Use @EnableConfigurationProperties & @Configuration.

@Configuration @EnableConfigurationProperties(CustomProperties.class) public class CustomAutoConfiguration {...}

Spring Boot – Consume Message Through Kafka, Save into ElasticSearch, and Plot into Grafana

- Use Kafka consumer. <br>- Store in ElasticSearch. <br>- Visualize with Grafana.

@KafkaListener(topics = "topicName") public void consume(String message) {...}

How to Implement AOP in Spring Boot Application?

- Use @Aspect, @Before, @After etc. <br>- Define pointcuts and advices.

@Aspect public class LoggingAspect { @Before("execution(* com.example..*.*(..))") public void logBefore() {...}}

Spring Boot – AOP(Aspect Oriented Programming)

- Modularize cross-cutting concerns. <br>- Separate business logic from aspect code.

@Aspect public class MyAspect {...}

Spring Boot – Cache Provider

- Use caching annotations. <br>- Integrate cache providers like EhCache, Redis.

@Cacheable("items") public Item getItem(Long id) {...}

Spring Boot – AOP Around Advice

- Execute advice around a method execution. <br>- Use @Around annotation.

@Around("execution(* com.example.service.*.*(..))") public Object logAround(ProceedingJoinPoint joinPoint) {...}

Spring Boot – Auto-configuration

- Spring Boot auto-configures beans. <br>- Customize behavior with application properties.

@SpringBootApplication

Spring Boot – EhCaching

- Integrate EhCache for caching. <br>- Use standard caching annotations.

@Cacheable(value="users", key="#userI




Topic

Topic Content/Answer

JAVA Code Example

Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat

- Starter Web provides tools for building web applications. <br>- Starter Tomcat provides embedded Tomcat.

spring-boot-starter-web vs. spring-boot-starter-tomcat in pom.xml

Spring Boot Actuator

- Provides production-ready features. <br>- Monitor and manage application.

spring-boot-starter-actuator

Spring Boot – Starter Test

- Support for testing Spring components. <br>- JUnit, Mockito, AssertJ.

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency>

Spring Boot – Exception Handling

- Handle exceptions using @ControllerAdvice or @ExceptionHandler.

@ControllerAdvice public class GlobalExceptionHandler {...}

Spring Boot – Project Deployment Using Tomcat

- Deploy Spring Boot app on external Tomcat server. <br>- Create WAR file.

spring-boot-starter-tomcat

Spring Boot – Difference Between AOP and OOP

- OOP: Object-oriented principles. <br>- AOP: Aspect-oriented principles. Modularizes cross-cutting concerns.

-

Spring Boot – Difference Between AOP and AspectJ

- AOP: Spring's support for aspect-oriented programming. <br>- AspectJ: Standalone AOP framework.

-

Spring Boot – Logging

- Uses Logback by default. <br>- Configure using application.properties.

logger.info("This is an info log.");

Advantages of Spring Boot JDBC

- Simplified database access. <br>- Integrated connection pooling.

JdbcTemplate jdbcTemplate;

Spring Boot – Packaging

- Package as JAR or WAR. <br>- Embedded servers for standalone execution.

spring-boot-maven-plugin in pom.xml

Spring Boot – JDBC

- Database connectivity. <br>- Use JdbcTemplate.

jdbcTemplate.queryForObject("SELECT ...");

Spring Boot – AOP After Throwing Advice

- Run advice after a method throws an exception.

@AfterThrowing(pointcut = "execution(* com.example..*.*(..))", throwing = "ex") public void afterThrowingAdvice(Exception ex) {...}

Spring Boot – AOP After Returning Advice

- Run advice after a method successfully returns a result.

@AfterReturning(pointcut = "execution(* com.example..*.*(..))", returning = "result") public void afterReturningAdvice(Object result) {...}

Spring Boot – Multi-Module Project

- Split project into multiple sub-modules. <br>- Helps in modularizing larger projects.

spring-boot-multi-module-project in pom.xml

Spring Boot – AOP After Advice

- Run advice after a method regardless of its outcome.

@After("execution(* com.example..*.*(..))") public void afterAdvice() {...}

Spring Boot – AOP Before Advice

- Run advice before a method is executed.

@Before("execution(* com.example..*.*(..))") public void beforeAdvice() {...}

Spring Boot – DevTools

- Provides automatic restart, live reload. <br>- Development-time features.

spring-boot-devtools in pom.xml

Spring Boot – Dependency Management

- Manages common dependencies. <br>- Ensures compatibility between dependencies.

spring-boot-dependencies in pom.xml

Spring Boot – Caching

- Improve performance. <br>- Cache frequently-used data.

@EnableCaching

Spring Boot – Starter Web

- Starter for building web applications. <br>- Includes Tomcat, MVC framework.

spring-boot-starter-web in pom.xml

Spring Boot – Difference Between @Service Annotation and @Repository Annotation

- @Service: Annotated at service layer. <br>- @Repository: Annotated at DAO layer, deals with database operations.

@Service public class MyService {...} vs. @Repository public interface MyRepository extends JpaRepository<MyEntity, Long> {...}




Topic

Topic Content/Answer

JAVA Code Example

Unit Testing in Spring Boot Project using Mockito and Junit

- Implement unit tests for Spring components. <br>- Mock dependencies using Mockito.

@Mock BeanName beanName; <br> @Test public void methodName() {...}

Spring Boot – Thymeleaf with Example

- Template engine. <br>- Render HTML views.

return "viewName"; in controller

Spring Boot – MongoRepository with Example

- Provides CRUD operations for MongoDB. <br>- Spring Data's repository abstraction.

public interface MyDocumentRepository extends MongoRepository<MyDocument, String> {...}

Spring Boot – Integrating Hibernate and JPA

- Combine JPA's ORM capabilities with Hibernate.

spring.datasource.url=jdbc:... in application.properties

Spring Boot JpaRepository with Example

- Provides CRUD operations for JPA entities. <br>- Extend JpaRepository<EntityType, IDType>.

public interface MyEntityRepository extends JpaRepository<MyEntity, Long> {...}

Spring Boot – CRUD Operations using MongoDB

- Create, Read, Update, Delete operations with MongoDB database.

mongoOperations.find(...), mongoOperations.save(...), etc.

Spring Boot – Spring Data JPA

- Simplify database access. <br>- Leverage CRUD operations.

@Entity public class MyEntity {...}

Upload Multiple Files in Spring Boot using JPA, Thymeleaf, Multipart

- Upload and store multiple files. <br>- Use MultipartFile for file handling.

@PostMapping("/upload") public String uploadFiles(@RequestParam("files") MultipartFile[] files) {...}

Spring Boot – Difference Between CrudRepository and JpaRepository

- CrudRepository: basic CRUD operations. <br>- JpaRepository: CRUD + JPA specific operations.

-

Spring Boot – CrudRepository with Example

- Provides basic CRUD operations. <br>- Extend CrudRepository<EntityType, IDType>.

public interface MyEntityRepository extends CrudRepository<MyEntity, Long> {...}

Spring Boot – application.yml/application.yaml File

- Externalized configuration. <br>- Define properties and profiles.

server.port: 8080 in application.yml

Spring Boot – CRUD Operations using MySQL Database

- Use JPA to perform CRUD operations on MySQL.

spring.datasource.url=jdbc:mysql://localhost:3306/mydb in application.properties

How to Implement One to Many Mapping in Spring Boot?

- Use JPA annotations. <br>- @OneToMany for one-to-many relationships.

@OneToMany(mappedBy = "parentEntity") private Set<ChildEntity> children;

How to Run Your First Spring Boot Application in Eclipse IDE?

- Setup Spring Boot in Eclipse. <br>- Right-click on project > Run As > Spring Boot App.

-

How to Run Spring Boot Application?

- Use SpringApplication.run() in main method.

public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); }

Spring Boot – Application Properties

- Configure application settings. <br>- Define in application.properties file.

spring.datasource.username=root in application.properties

Spring Boot – H2 Database

- In-memory database. <br>- Used for development and testing.

spring.datasource.url=jdbc:h2:mem:mydb in application.properties

Spring Boot – CRUD Operations

- Standard database operations: Create, Read, Update, Delete.

repository.save(entity);, repository.findById(id);, etc.

Spring Boot – REST Example

- Expose RESTful endpoints. <br>- Use @RestController and @RequestMapping.

@RestController public class MyController { @GetMapping("/items") public List<Item> getItems() {...} }




Topic

Topic Content/Answer

JAVA Code Example

How to Run Your First Spring Boot Application in IntelliJ IDEA?

- Open IntelliJ IDEA. <br>- Open/import Spring Boot project. <br>- Click 'Run'.

Right-click on the main class > Run 'ClassName.main()'

Spring Boot – Change Port

- Customize the default port for Spring Boot application.

server.port=8081 in application.properties

Spring Boot – Hello World Example

- Simple Spring Boot application to display "Hello World".

@RestController public class HelloWorldController { @GetMapping("/") public String hello() { return "Hello World"; } }

What is Command Line Runner Interface in Spring Boot?

- Executes specific code at application startup.

public class MyApplication implements CommandLineRunner { @Override public void run(String... args) { // Code here } }

How to Create and Setup Spring Boot Project in Eclipse IDE?

- Setup Spring Boot in Eclipse. <br>- Use Spring Initializr or import existing project.

File > Import > Existing Maven Project

How to Create and Setup Spring Boot Project in Spring Tool Suite?

- Use Spring Tool Suite's built-in support for Spring Boot. <br>- Import or create new project.

File > New > Spring Starter Project

How to Make a Simple RestController in Spring Boot?

- Define RESTful endpoints using @RestController.

@RestController public class MyController { @GetMapping("/endpoint") public String method() { return "Response"; } }

How to Implement Simple Authentication in Spring Boot?

- Use Spring Security for authentication. <br>- Define security configurations.

@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { ... }

What is PathVariable in the Spring Boot?

- Annotation to capture URL template values.

@GetMapping("/items/{id}") public String getItem(@PathVariable String id) { ... }

How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA?

- Use Spring Initializr for project setup. <br>- Open project in IntelliJ and run.

File > Open > Select generated project from Spring Initializr

How to Get the Body of Request in Spring Boot?

- Extract request body data in controller methods.

@PostMapping("/endpoint") public String method(@RequestBody String body) { ... }

How to Make Put Request in Spring Boot?

- Implement an endpoint to handle HTTP PUT requests.

@PutMapping("/endpoint") public String updateMethod(@RequestBody DataClass data) { ... }

Deploying Spring Boot Application with MySQL Database on Azure

- Deploy app on Azure. <br>- Setup MySQL on Azure and connect.

(Requires Azure configurations and application.properties setup)

How to Call or Consume External API in Spring Boot?

- Use RestTemplate or WebClient to consume external APIs.

RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

Spring Boot – Starter Parent

- Provides default configurations. <br>- Simplifies Maven configuration.

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> ... </parent>

Spring Boot – Customize the Jackson ObjectMapper

- Modify how Java objects are serialized/deserialized.

@Bean public ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); ... return mapper; }

Spring Boot – Starters

- Pre-configured set of dependencies. <br>- Simplify build and application configurations.

Add dependency: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

Spring Boot – Code Structure

- Follows specific layout. <br>- Separate packages for controllers, services, repositories, etc.

src/main/java/com.example/myapp/Controller/, src/main/java/com.example/myapp/Service/, etc.

Spring MVC




Topic

Topic Content/Answer

JAVA Code Example

Introduction to Spring MVC

- Framework for building web applications. <br>- MVC pattern: Model, View, Controller.

N/A

Spring MVC using Java-based configuration

- Configuring Spring MVC without XML. <br>- Use Java classes for configuration.

@Configuration @EnableWebMvc public class WebConfig implements WebMvcConfigurer { ... }

ViewResolver in Spring MVC

- Determines views based on logical view names.

@Bean public ViewResolver viewResolver() { InternalResourceViewResolver vr = new InternalResourceViewResolver(); ... }

How to Create Your First Model in Spring MVC?

- Model represents data in MVC pattern.

public class User { private String name; // getters and setters }

How to Create Your First View in Spring MVC?

- View is responsible for presenting data.

@Controller public class ViewController { @GetMapping("/") public String viewPage() { return "viewName"; } }

Spring MVC CRUD with Example

- Create, Read, Update, Delete operations using Spring MVC.

@PostMapping("/create") public String create(User user) { ... }

Create and Run Your First Spring MVC Controller in Eclipse/Spring Tool Suite

- Setup a controller in Eclipse or STS. <br>- Map routes to controller methods.

@Controller public class MyController { @GetMapping("/hello") public String hello() { return "helloPage"; } }

What is Dispatcher Servlet in Spring?

- Central servlet that handles all requests. <br>- Front controller in Spring MVC.

Defined in web.xml or Java Configuration

Spring – Shortcut to Create Dispatcher Servlet in Eclipse/Spring Tool Suite

- Faster way to setup DispatcherServlet using IDE.

Specific to IDE settings

WebApplicationContext in Spring MVC

- Extension of ApplicationContext. <br>- Specific to web applications.

N/A

Spring – Multi Action Controller with Example

- Controller with multiple actions/methods.

public class MultiActionController { public ModelAndView actionOne(HttpServletRequest request, HttpServletResponse response) { ... } }

Spring MVC – Exception Handling

- Handle exceptions in Spring MVC. <br>- Use @ExceptionHandler or global error handler.

@ExceptionHandler(Exception.class) public ModelAndView handleAllExceptions(Exception ex) { ... }

Spring – How to Load Literal Values From Properties File

- Load values from .properties file. <br>- Use @Value to inject properties.

@Value("${property.name}") private String propertyName;

Spring MVC – Multiple View Page

- Return different views based on logic or input.

@GetMapping("/view") public String getView(boolean condition) { return condition ? "view1" : "view2"; }

Spring MVC – Custom Validation

- Validate data using custom rules. <br>- Implement Validator interface.

public class UserValidator implements Validator { @Override public boolean supports(Class<?> clazz) { ... } ... }




Topic

Topic Content/Answer

JAVA Code Example

Difference Between ApplicationContext and WebApplicationContext in Spring MVC

- ApplicationContext: General application context. <br>- WebApplicationContext: Context for web applications.

N/A

Difference Between @Component, @Repository, @Service, and @Controller Annotations in Spring

- General-purpose stereotype. <br>- DAO layer. <br>- Service layer. <br>- Controller layer in MVC.

@Component, @Repository, @Service, @Controller

Difference Between @Controller and @Service Annotation in Spring

- @Controller: Handles HTTP requests. <br>- @Service: Business logic layer.

@Controller public class MyController {}, <br> @Service public class MyService {}

Difference Between @Controller and @RestController Annotation in Spring

- @Controller: Returns views. <br>- @RestController: Returns data directly.

@Controller public class MyController {}, <br> @RestController public class MyRestController {}

Spring MVC – RequestParam Annotation

- Annotation to extract values from URL parameters.

public String method(@RequestParam("name") String name) {}

Query String and Query Parameter in Spring MVC

- Query String: Part of URL after ?. <br>- Query Parameter: Key-value pairs in query string.

N/A

How to Make Post Request in Java Spring?

- Submit data to server.

@PostMapping("/endpoint") public ResponseEntity<?> method(@RequestBody DataClass data) { return ...; }

How to Make Delete Request in Spring?

- Remove resource from server.

@DeleteMapping("/endpoint/{id}") public ResponseEntity<?> deleteMethod(@PathVariable Long id) { return ...; }

How to Make get() Method Request in Java Spring?

- Retrieve data from server.

@GetMapping("/endpoint") public ResponseEntity<?> getMethod() { return ...; }

Spring @RequestMapping Annotation with Example

- Map web requests to methods. <br>- Can be used with GET, POST, PUT, DELETE etc.

@RequestMapping(value="/endpoint", method=RequestMethod.GET) public String method() { return ...; }

How to Capture Data using @RequestParam Annotation in Spring?

- Extract specific values from URL.

public String method(@RequestParam("paramName") String paramValue) {}

Spring @ResponseBody Annotation with Example

- Return data directly as response. <br>- Converts return value to HTTP response body.

@GetMapping("/data") @ResponseBody public DataClass getData() { return new DataClass(); }

Spring MVC Project – Retrieving Population, Area and Region Details using Rest API

- Get details via a RESTful API.

@GetMapping("/details") public ResponseEntity<?> getDetails(@RequestParam String region) { return ...; }

Spring MVC – Last 24-Hour Cryptocurrency Data using REST API

- Fetch and display cryptocurrency data from last 24 hours.

@GetMapping("/cryptoData") public ResponseEntity<?> getCryptoData() { return ...; }

Spring MVC – Sample Project For Finding Doctors Online with MySQL

- Search for doctors and view details stored in MySQL.

@GetMapping("/findDoctor") public ResponseEntity<?> findDoctor(@RequestParam String specialization) { return ...; }

Spring MVC JSTL Configuration

- Configuring JavaServer Pages Standard Tag Library in Spring MVC.

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


Topic

Topic Content/Answer

JAVA Code Example

Spring MVC with MySQL – Sample Project For Calculating Electricity Bill

- Calculate bills using data in MySQL. <br>- Integration of Spring MVC with database.

@Controller public class BillController { @Autowired BillService billService; ... }

Spring MVC – Comparison of Cryptocurrencies using REST API

- Fetch and compare data from cryptocurrency APIs.

@GetMapping("/compareCrypto") public String compare(@RequestParam("crypto1") String crypto1, ...)

Spring MVC – Get Probability of a Gender by Providing a Name using REST API

- Predict gender based on name. <br>- Fetch probability from an external API.

@GetMapping("/getGender") public String getGenderProbability(@RequestParam("name") String name, ...)

Get Time Zone by Providing Latitude and Longitude using Spring MVC and REST API

- Fetch timezone information based on coordinates.

@GetMapping("/getTimezone") public ResponseEntity<?> getTimezone(@RequestParam("lat") double lat, ...)

Spring MVC with MySQL and Junit – Finding Employees Based on Location

- Find employees in a particular location from MySQL. <br>- Test functionalities using Junit.

@GetMapping("/findEmployees") public List<Employee> findEmployeesByLocation(@RequestParam("location") String location)

Spring MVC – Get University/College Details via REST API

- Fetch university details through an external API.

@GetMapping("/getUniversityDetails") public String getDetails(@RequestParam("name") String name, ...)

Spring MVC – JSTL forEach Tag with Example

- Iterating over collections in JSP using JSTL tags.

<c:forEach items="${list}" var="item"> ${item} </c:forEach>

Spring MVC – Iterating List on JSP using JSTL

- Display list items on JSP using JSTL iteration.

<c:forEach items="${list}" var="item"> <li>${item}</li> </c:forEach>

Two-Way Data Binding in Spring MVC with Example

- Bind data from object to UI and vice versa.

<form:form modelAttribute="dataObj"> <form:input path="property" /> </form:form>

Spring MVC – Basic Example using JSTL

- Create a basic view using JSTL in Spring MVC.

<c:out value="${data}" />

Spring MVC @ModelAttribute Annotation with Example

- Populate a model object from form or other source.

public String method(@ModelAttribute("dataObj") DataClass data, BindingResult result)

Data Transfer Object (DTO) in Spring MVC with Example

- Use DTO for data transfer between layers.

public class DataDTO { private String property; ... }

Spring MVC – Capture and Display the Data from Registration Form

- Fetch user input from registration form and display.

@PostMapping("/register") public String register(@ModelAttribute("user") User user, Model model)

Spring MVC – Create Registration Form using Form Tag Library

- Use Spring's form tag library for creating forms.

<form:form modelAttribute="user"> <form:input path="username" /> </form:form>

Data Binding in Spring MVC with Example

- Bind form data to a model object.

<form:form modelAttribute="dataObj"> <form:input path="property" /> </form:form>

Spring MVC – Pagination with Example

- Display data in a paginated format.

@GetMapping("/data") public String viewPage(Model model, @RequestParam("pageId") int pageId, ...)

Spring MVC Integration with MySQL

- Connect Spring MVC with MySQL database.

@Autowired DataSo


Topic

Topic Content/Answer

JAVA Code Example

OpenSource REST API URL and Retrieving Data From it By Using Spring MVC

- Fetch data from an open-source REST API. <br> - Use Spring MVC to process the retrieved data.

@RestController public class ApiController { @GetMapping("/data") public ResponseEntity<?> fetchData() { ... }

How to Resolve WEB xml is missing and failOnMissingWebXml is set to true in Eclipse/STS?

- Issues with web.xml file missing in the project. <br> - Adjust configurations to bypass the error.

// Adjust Maven configurations

Spring MVC Application Without web.xml File

- Build Spring MVC application without traditional web.xml. <br> - Use Java configurations instead.

@Configuration @EnableWebMvc public class WebConfig { ... }

Spring MVC – Listbox

- Implement list boxes in Spring MVC forms.

<form:select path="options" items="${listOptions}" />

Spring MVC – Multiple Resolver Mapping

- Handle multiple view resolvers in a single Spring MVC application.

@Configuration public class MvcConfig { @Bean public ViewResolver firstResolver() { ... } }

How to Extract TV Show Details via REST API and Spring MVC?

- Use REST API to fetch TV show details. <br> - Display it using Spring MVC.

@Controller public class TvShowController { @GetMapping("/showDetails") public String showDetails() { ... } }

Spring MVC File Upload

- Implement file upload feature in Spring MVC.

@PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { ... }

Spring MVC – Tiles

- Integrate Apache Tiles with Spring MVC for templating views.

@Configuration public class TilesConfig { ... }

Spring MVC – Text Box

- Implement text boxes in Spring MVC forms.

<form:input path="textField" />

Spring MVC – Multiple Controller

- Have more than one controller in a Spring MVC application.

@Controller public class FirstController { ... } @Controller public class SecondController { ... }

Spring MVC – Model Interface

- Use the Model interface for passing attributes to views.

public String method(Model model) { model.addAttribute("key", "value"); ... }

Spring MVC – Number Validation

- Implement validations for number fields in forms.

@NumberFormat(style=Style.NUMBER) @NotNull private BigDecimal price;

Spring MVC – Form Checkbox

- Implement checkboxes in Spring MVC forms.

<form:checkbox path="agree" />

Spring MVC – Form Radio Button

- Implement radio buttons in Spring MVC forms.

<form:radiobutton path="gender" value="male" />

Spring MVC – Form Drop-Down List

- Implement drop-down lists in Spring MVC forms.

<form:select path="options" items="${listOptions}" />

Spring MVC – TextArea

- Implement text areas in Spring MVC forms.

<form:textarea path="comments" />

Spring MVC – Hidden Field

- Use hidden fields in Spring MVC forms.

<form:hidden path="id" />

Spring MVC – Regular Expression Validation

- Implement regex validation for form fields.

@Pattern(regexp="^[a-zA-Z0-9]+$") private String data;

Spring MVC – Password

- Implement password fields in Spring MVC forms.

<form:password path="password" />

Spring MVC – Form Tag Library

- Use the Spring MVC form tag library for building forms.

<form:form modelAttribute="user" > ... </form:form>

Spring MVC – Form Text Field

- Implement text fields using Spring MVC form tags.

<form:input path="username" />

Spring MVC – Validation

- Implement validations for form data in Spring MVC.

@Controller @RequestMapping("/form") public class FormController { @InitBinder public void initBinder(...) { ... } }

Spring MVC – Form Handling

- Process submitted form data in Spring MVC.

@PostMapping("/submitForm") public String handleForm(@ModelAttribute("data") FormData data, BindingResult result)

How to Create a Project using Spring MVC and Hibernate 5?

- Set up a project that integrates both Spring MVC and Hibernate ORM.

@Entity public class User { ... }

Spring MVC – Getting Cryptocurrency Details using REST API

- Fetch details of various cryptocurrencies using an external REST API. <br> - Display it using Spring MVC.

@Controller public class CryptoController { @GetMapping("/cryptoDetails") public String getCryptoDetails() { ... } }

Spring MVC – Get Exchange Rate Values using REST API

- Fetch exchange rate details from an external REST API. <br> - Display the fetched data using Spring MVC.

`@Controller public class ExchangeRateController { @GetMapping("/exchangeRates") public String getRates() { ...

Spring with REST API




Topic

Topic Content/Answer

JAVA Code Example

Spring REST JSON Response

- Send JSON responses from a Spring REST API.

@GetMapping("/data") public ResponseEntity<String> getData() { return ResponseEntity.ok("{\"data\":\"value\"}"); }

Spring – REST XML Response

- Send XML responses from a Spring REST API.

@GetMapping(value = "/xmlData", produces = MediaType.APPLICATION_XML_VALUE) public MyXmlObject getXmlData() {...}

Spring – REST Controller

- Define RESTful controllers in Spring.

@RestController public class MyRestController { @GetMapping("/endpoint") public String getEndpoint() { ... } }

Spring MVC – Getting Cryptocurrency Details using REST API

- Fetch details of various cryptocurrencies using an external REST API.

@GetMapping("/cryptoDetails") public ResponseEntity<List<Crypto>> getCryptoDetails() {...}

Spring MVC – Get Exchange Rate Values using REST API

- Fetch exchange rate values from an external REST API.

@GetMapping("/exchangeRates") public ResponseEntity<Map<String, Double>> getExchangeRates() {...}

Spring Boot – Introduction to RESTful Web Services

- Introduction to creating RESTful web services using Spring Boot.

@SpringBootApplication public class RestfulServiceApplication { public static void main(String[] args) { ... } }

How to create a REST API using Java Spring Boot

- Steps to create a basic REST API with Spring Boot.

@RestController @RequestMapping("/api") public class MyController { @GetMapping("/data") public Data getData() {...}

Easiest Way to Create REST API using Spring Boot

- Simplified process to quickly create a REST API using Spring Boot.

@SpringBootApplication public class EasyApiApplication { ... }

JSON using Jackson in REST API Implementation with Spring Boot

- Use Jackson library to handle JSON serialization and deserialization in a Spring Boot REST API.

@GetMapping("/jsonData") public MyObject getJsonData() {...}

How to Make a Simple RestController in Spring Boot?

- Create a basic RestController to handle HTTP requests in Spring Boot.

@RestController public class SimpleController { @GetMapping("/simple") public String simpleEndpoint() { return "Hi"; } }

Spring MVC Project – Retrieving Population, Area and Region Details using Rest API

- Fetch details like population, area, and region using an external REST API.

@GetMapping("/regionDetails") public RegionDetails getDetails() {...}

Spring MVC – Last 24 Hour Cryptocurrency Data using REST API

- Fetch cryptocurrency data of the last 24 hours using an external REST API.

@GetMapping("/crypto24Hours") public Crypto24HoursData getCryptoData() {...}

Spring MVC – Comparison of Cryptocurrencies using REST API

- Compare different cryptocurrencies based on certain metrics using an external REST API.

@GetMapping("/cryptoComparison") public CryptoComparisonData compareCryptos() {...}

Spring MVC – Get Probability of a Gender by Providing a Name using REST API

- Predict the gender of a name by fetching data from an external REST API.

@GetMapping("/predictGender") public GenderPrediction getGenderPrediction(@RequestParam String name) {...}




Topic

Topic Content/Answer

JAVA Code Example

Get Time Zone by Providing Latitude and Longitude

- Use REST API to determine timezone based on latitude and longitude.

@GetMapping("/timezone") public ResponseEntity<TimeZone> getTimeZone(@RequestParam double lat, @RequestParam double lon) {...}

Spring MVC – Get University/College Details via REST API

- Retrieve details of universities/colleges through an external REST API.

@GetMapping("/university") public ResponseEntity<University> getUniversityDetails(@RequestParam String name) {...}

OpenSource REST API URL and Retrieving Data

- Access and retrieve data from an open-source REST API using Spring MVC.

@GetMapping("/openSourceData") public ResponseEntity<Data> getOpenSourceData() {...}

How to Extract TV Show Details via REST API and Spring MVC?

- Fetch TV show details using an external REST API within a Spring MVC framework.

@GetMapping("/tvShowDetails") public ResponseEntity<TvShow> getTvShowDetails(@RequestParam String showName) {...}

Spring MVC – Getting Cryptocurrency Details using REST API

- Retrieve details of various cryptocurrencies using an external REST API.

@GetMapping("/cryptoDetails") public ResponseEntity<List<Crypto>> getCryptoDetails() {...}

Spring MVC – Get Exchange Rate Values using REST API

- Fetch exchange rate values from an external REST API.

@GetMapping("/exchangeRates") public ResponseEntity<Map<String, Double>> getExchangeRates() {...}

Spring Boot – Introduction to RESTful Web Services

- Introduction to creating RESTful web services using Spring Boot.

@SpringBootApplication public class RestfulServiceApplication { public static void main(String[] args) { ... } }

How to create a basic application in Java Spring Boot

- Steps to create and run a simple Spring Boot application.

@SpringBootApplication public class BasicApplication { public static void main(String[] args) { SpringApplication.run(BasicApplication.class, args); } }

How to create a REST API using Java Spring Boot

- Set up and deploy a REST API using Spring Boot.

@RestController @RequestMapping("/api") public class ApiController { @GetMapping("/data") public Data getData() {...} }

Easiest Way to Create REST API using Spring Boot

- A simplified approach to quickly creating a REST API with Spring Boot.

@SpringBootApplication public class EasyApiApplication { ... }

Spring – RestTemplate

- A tool from Spring framework which offers client-side HTTP access. Useful for consuming REST.

RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);


Topic

Topic Content/Answer

JAVA Code Example

JSON using Jackson in REST API Implementation with Spring Boot

- Utilize Jackson to serialize and deserialize Java objects to/from JSON in Spring Boot REST APIs.

@GetMapping("/data") public ResponseEntity<Data> getData() { return new ResponseEntity<>(data, HttpStatus.OK); }

Spring Boot – REST Example

- A basic example of setting up RESTful endpoints using Spring Boot.

@RestController @RequestMapping("/example") public class RestExampleController { @GetMapping public String getExample() { return "Hello World"; } }

How to Make a Simple RestController in Spring Boot?

- Demonstrates creating a basic REST controller in Spring Boot.

@RestController public class SimpleController { @GetMapping("/simple") public String getSimple() { return "Simple Response"; } }

Difference Between @Controller and @RestController Annotation in Spring

- @Controller is used for MVC web applications. - @RestController is for RESTful web services.

No specific code example as it is more of a conceptual topic.

Spring MVC Project – Retrieving Population, Area and Region Details using Rest API

- Fetch population, area, and region details via an external REST API using Spring MVC.

@GetMapping("/populationDetails") public PopulationData getDetails() {...}

Spring MVC – Last 24 Hour Cryptocurrency Data using REST API

- Retrieve data for cryptocurrencies from the last 24 hours using a REST API.

@GetMapping("/crypto24h") public List<Crypto> getCryptoLast24h() {...}

Spring MVC – Comparison of Cryptocurrencies using REST API

- Compare different cryptocurrencies' details through REST API.

@GetMapping("/cryptoCompare") public CryptoComparison compareCryptos() {...}

Spring MVC – Get Probability of a Gender by Providing a Name using REST API

- Determine the likely gender of a given name using a REST API.

@GetMapping("/genderProbability") public GenderProbability getGenderProbability(@RequestParam String name) {...}

Get Time Zone by Providing Latitude and Longitude using Spring MVC and REST API

- Fetch the timezone for given coordinates using Spring MVC with REST.

@GetMapping("/timezone") public TimeZone getTimeZone(@RequestParam double lat, @RequestParam double lon) {...}

Spring MVC – Get University/College Details via REST API

- Get details of universities/colleges using a REST API in Spring MVC.

@GetMapping("/universityDetails") public University getUniversityDetails(@RequestParam String universityName) {...}

OpenSource REST API URL and Retrieving Data From it By Using Spring MVC

- Retrieve data from an open-source REST API using Spring MVC.

@GetMapping("/openSourceData") public Data getOpenSourceData() {...}

How to Extract TV Show Details via REST API and Spring MVC?

- Fetch details about TV shows using a REST API within Spring MVC.

@GetMapping("/tvShowDetails") public TvShow getTvShowDetails(@RequestParam String showName) {...}

Spring MVC – Getting Cryptocurrency Details using REST API

- Fetch details of various cryptocurrencies using an external REST API.

@GetMapping("/cryptoDetails") public List<Crypto> getCryptoDetails() {...}

Spring MVC – Get Exchange Rate Values using REST API

- Retrieve the latest exchange rate values using an external REST API.

@GetMapping("/exchangeRates") public Map<String, Double> getExchangeRates() {...}

Spring Data



Topic

Topic Content/Answer

JAVA Code Example

What is Spring Data JPA?

- A part of Spring Data framework. - Simplifies database operations. - Built on top of JPA.

public interface UserRepository extends JpaRepository<User, Long> {}

JPA vs Hibernate

- JPA is a specification. - Hibernate is an implementation of JPA.

No specific code example as it is more of a conceptual topic.

Spring Data JPA – Find Records From MySQL

- Use Repository to fetch records from MySQL.

List<User> users = userRepository.findAll();

Spring Data JPA – Delete Records From MySQL

- Delete records using Spring Data JPA repository.

userRepository.deleteById(userId);

Spring Data JPA – @Table Annotation

- Specifies the table for an entity.

@Entity @Table(name = "users") public class User {...}

Spring Data JPA – Insert Data in MySQL Table

- Insert data into a table using Repository.

User user = new User(); userRepository.save(user);

Spring Data JPA – Attributes of @Column Annotation with Example

- Customizes column definitions.

@Column(name = "user_name", length = 50) private String userName;

Spring Data JPA – @Column Annotation

- Specifies a mapped column for a field.

@Column(name = "user_email") private String email;

Spring Data JPA – @Id Annotation

- Marks a field as the primary key.

@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;

Introduction to the Spring Data Framework

- A framework to simplify database access and supports various data sources.

No specific code example as it is an introductory topic.

How to access database using Spring Data JPA

- Use Spring Data JPA repositories for CRUD operations.

public interface UserRepository extends JpaRepository<User, Long> {}

How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?

- Setup project using Maven. - Integrate Spring Boot, MySQL, and Spring Data JPA.

pom.xml configuration with dependencies: Spring Boot, MySQL driver, and Spring Data JPA.

Spring Boot – Integrating Hibernate and JPA

- Setup Hibernate as the JPA provider in a Spring Boot project.

spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.jpa.hibernate.ddl-auto=update in application.properties

Spring Boot JpaRepository with Example

- Provides CRUD operations for an entity.

public interface UserRepository extends JpaRepository<User, Long> { User findByEmail(String email); }

Spring Boot – Spring Data JPA

- Spring Boot's way to simplify database operations using Spring Data JPA.

@Entity public class User {...} and public interface UserRepository extends JpaRepository<User, Long> {}

Spring JDBC




Topic

Topic Content/Answer

JAVA Code Example

Spring JDBC Template

- Simplifies database interactions. - Reduces boilerplate code.

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

Spring JDBC Example

- Demonstrates basic CRUD operations using Spring JDBC.

jdbcTemplate.update("INSERT INTO users(name) VALUES(?)", "John");

Spring – SimpleJDBCTemplate with Example

- Deprecated template. - Simplifies database operations with less boilerplate code.

SimpleJdbcTemplate template = new SimpleJdbcTemplate(dataSource);

Spring – Prepared Statement JDBC Template

- Safely execute SQL queries. - Prevent SQL injection.

jdbcTemplate.update("INSERT INTO users(name) VALUES(?)", new PreparedStatementSetter(){ public void setValues(PreparedStatement ps){ ps.setString(1, "John"); }});

Spring – NamedParameterJdbcTemplate

- Enhanced template to support named parameters in SQL queries.

NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(dataSource); Map<String, Object> params = new HashMap<>(); params.put("name", "John"); namedTemplate.update("INSERT INTO users(name) VALUES(:name)", params);

Spring – Using SQL Scripts with Spring JDBC + JPA + HSQLDB

- Execute SQL scripts for database setup and teardown.

@Sql({ "/schema.sql", "/data.sql" }) @SpringBootTest

Spring – ResultSetExtractor

- Extracts data from a ResultSet.

jdbcTemplate.query("SELECT * FROM users", new ResultSetExtractor<List<User>>(){ public List<User> extractData(ResultSet rs) throws SQLException { List<User> list = new ArrayList<>(); while(rs.next()){ list.add(new User(rs.getString("name"))); } return list; }});

Spring ORM or Spring Hibernate



Topic

Topic Content/Answer

JAVA Code Example

Spring Hibernate Configuration

- Integrates Spring with Hibernate. - Defines session factory, data source, etc.

@Bean public LocalSessionFactoryBean sessionFactory() {...}

Hibernate Lifecycle

- Describes states: transient, persistent, detached.

Session session = sessionFactory.openSession(); session.save(entity);

JPA vs Hibernate

- JPA: specification; Hibernate: JPA implementation. - JPA: standards-based; Hibernate: additional features.

@Entity // JPA annotation

Spring ORM using Hibernate

- Spring's integration for Object-Relational Mapping with Hibernate.

@Autowired SessionFactory sessionFactory;

Spring Boot – Validation using Hibernate Validator

- Use annotations to validate bean properties.

@NotNull @Size(min=2, max=30) private String name;

Create Project Using Spring MVC & Hibernate 5

- Set up a Spring MVC project with Hibernate 5 for ORM.

@SpringBootApplication

Hibernate – One-to-One Mapping

- Represents one-to-one relationship between entities.

@OneToOne(cascade = CascadeType.ALL) @JoinColumn(name="address_id") private Address address;

Spring Boot – Integrating Hibernate and JPA

- Configure Spring Boot to use Hibernate as JPA provider.

spring.datasource.hibernate.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

Hibernate – Cache Eviction

- Manually removing specific objects from the cache.

sessionFactory.getCache().evictEntityRegion(MyClass.class);

Hibernate – Cache Expiration

- Set a duration after which cache entries expire.

hibernate.cache.expiry_time = 60000

Hibernate – First & Second Level Cache

- 1st level: Session; 2nd level: SessionFactory.

@Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)

Hibernate – Save Images & Other Values

- Store BLOBs and CLOBs in the database.

@Lob @Column(name="image_data") private byte[] image;

Hibernate – Pagination

- Break large result set into smaller chunks.

Query query = session.createQuery("FROM Entity"); query.setFirstResult(0); query.setMaxResults(10);


Topic

Topic Content/Answer

JAVA Code Example

Hibernate – Different Cascade Types

- Cascade types like ALL, PERSIST, MERGE, REMOVE, etc. - Defines operations cascaded from parent to child entities.

@OneToMany(cascade = CascadeType.ALL) private Set<Child> children;

Hibernate Native SQL Query

- Execute native SQL queries.

String sql = "SELECT * FROM table"; List results = session.createNativeQuery(sql).list();

Hibernate – Caching

- Improve performance. - First-level (session) and second-level (session factory) caches.

@Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_ONLY)

@Embeddable & @Embedded Annotation

- Embedding one entity inside another as a component.

@Embeddable public class Address {...} @Embedded private Address address;

Hibernate – Eager/Lazy Loading

- Strategy to load related entities. Eager: immediately, Lazy: on-demand.

@OneToMany(fetch = FetchType.LAZY) private Set<Child> children;

Hibernate – get() & load() Method

- get(): returns null if not found, load(): returns proxy & throws exception if not found.

Entity e = session.get(Entity.class, id); Entity e2 = session.load(Entity.class, id);

Hibernate Validator

- Validate bean properties using annotations.

@NotNull @Size(min=5, max=20) private String name;

CRUD Operations using Hibernate

- Create, Read, Update, Delete operations with Hibernate.

session.save(entity); session.get(Entity.class, id); session.update(entity); session.delete(entity);

Hibernate Example without IDE

- Setting up and running a Hibernate example without using an Integrated Development Environment.

Configuration config = new Configuration().configure(); SessionFactory sf = config.buildSessionFactory();

Hibernate – Inheritance Mapping

- Mapping strategies like Single Table, Table Per Class, and Joined.

@Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE)

Automatic Table Creation Using Hibernate

- Hibernate's ability to generate database tables based on entities.

hibernate.hbm2ddl.auto = update

Hibernate – Batch Processing

- Insert/update multiple records efficiently in batches.

session.setJdbcBatchSize(50); for(Entity e: entities) { session.save(e); }

Hibernate – Component Mapping

- Map embedded objects as components of an entity.

@Embeddable public class Address {...} @Embedded private Address address;

Hibernate – Mapping List

- Map ordered collections with Hibernate.

@OrderColumn(name="sequence") @OneToMany private List<Child> children;

Hibernate – Collection Mapping

- Mapping Java collections to database tables.

@ElementCollection private Set<String> names;


Topic

Topic Content/Answer

JAVA Code Example

Hibernate – Bag Mapping

- Represents unordered collection. - Can contain duplicate elements.

@OneToMany @Bag private Collection<Item> items;

Difference Between List and Bag Mapping

- List: Ordered, Indexed collection. - Bag: Unordered, Can have duplicates.

List: @OrderColumn @OneToMany private List<Item> items; Bag: @Bag @OneToMany private Collection<Item> items;

Hibernate – SortedSet Mapping

- Represents sorted set in Hibernate. - Uses Java's TreeSet.

@OneToMany @SortNatural private SortedSet<Item> items;

Hibernate – SortedMap Mapping

- Represents a map that's sorted by its keys.

@OneToMany @MapKey @SortNatural private SortedMap<Key, Value> map;

Hibernate – Native SQL

- Ability to execute native SQL queries directly.

session.createSQLQuery("SELECT * FROM table_name").list();

Hibernate – Logging by Log4j using XML File

- Configure Hibernate logging using Log4j and XML configuration.

<logger name="org.hibernate.SQL"><level value="DEBUG"/></logger>

Hibernate – Many-to-One Mapping

- Represents many-to-one relationship between entities.

@ManyToOne @JoinColumn(name="foreign_key_column") private Entity entity;

Logging By Log4j Using Properties File

- Configure Hibernate logging with Log4j using properties file.

log4j.logger.org.hibernate.SQL=DEBUG

Table Per Concrete Class Using Annotation

- Each concrete class corresponds to a table in DB.

@Entity @Table(name = "concrete_class_name")

Table Per Subclass using Annotation

- Each subclass has its own table containing distinct fields plus fields inherited from superclass.

@Entity @Inheritance(strategy = InheritanceType.JOINED)

Hibernate – Interceptors

- Used to intercept operations before/after they occur.

sessionFactory.withOptions().interceptor(new MyInterceptor()).openSession();

Many-to-Many Mapping

- Represents many-to-many relationship between entities.

@ManyToMany @JoinTable(name="join_table_name") private Set<AnotherEntity> entities;

Types of Mapping

- Different association mappings like One-to-One, One-to-Many, Many-to-One, and Many-to-Many.

(Various examples based on different mapping types)

Hibernate – Criteria Queries

- Object-oriented way to query DB, instead of using SQL strings.

Criteria crit = session.createCriteria(Entity.class); crit.add(Restrictions.eq("field", value));




Topic

Topic Content/Answer

JAVA Code Example

Hibernate – Table Per Hierarchy using Annotation

- Single table for whole class hierarchy. - Discriminator column to distinguish between classes.

@Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="type")

Table Per Subclass Example using XML File

- Each subclass has its table. - Separate XML mapping for each class.

<subclass name="Subclass" extends="Parent" table="sub_table">

Hibernate – Table Per Hierarchy using XML File

- Single table for hierarchy. - XML mapping with discriminator column.

<class name="Parent" table="parent_table" discriminator-value="type">

Hibernate – Create POJO Classes

- Plain Old Java Object classes. - Represent DB tables without logic.

public class User { private int id; private String name; }

Hibernate – Web Application

- Web apps using Hibernate for DB operations.

@Controller public class UserController { @Autowired private SessionFactory sessionFactory; }

Hibernate – Table Per Concrete Class using XML File

- Each concrete class has its own table in DB. - Defined in XML mapping.

<class name="ConcreteClass" table="concrete_table">

Hibernate – Generator Classes

- For generating primary key values automatically.

<id name="id" type="long"> <generator class="native"/> </id>

Hibernate – SQL Dialects

- Convert Hibernate queries to DB specific SQL. - Configure dialect for specific DBMS.

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

Hibernate – Query Language

- Object-oriented query language. - Write queries against Java objects, not DB tables.

String hql = "FROM User"; Query query = session.createQuery(hql);

Difference Between ORM and JDBC

- ORM: Object-relational mapping, higher abstraction, no SQL for CRUD. - JDBC: Lower level, manual SQL, fine-grained control.

ORM: session.get(User.class, id); JDBC: resultSet = statement.executeQuery("SELECT * FROM users WHERE id = ?");

Hibernate – Annotations

- Metadata to provide configuration in code. - Alternative to XML mappings.

@Entity @Table(name = "users")

Hibernate Example using XML in Eclipse

- Use Hibernate tools in Eclipse. - Create mapping and config files using GUI.

(Dependent on Eclipse plugin)

Hibernate – Create Hibernate Configuration File with the Help of Plugin

- Use a plugin for generating hibernate.cfg.xml.

(Dependent on plugin specifics)

Hibernate Example using JPA and MySQL

- Using Java Persistence API with Hibernate. - Store and retrieve data from MySQL.

@Entity public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; }

Hibernate – One-to-Many Mapping

- One entity relates to multiple entities.

@Entity public class User { @OneToMany(mappedBy="user") private Set<Order> orders; }




Spring AOP



Topic

Topic Content/Answer

JAVA Code Example

Aspect-Oriented Programming and AOP in Spring Framework

- Introduces concerns like transaction management. - Separation of concerns in modular aspects.

@Aspect public class LoggingAspect { }

Spring Boot – AOP Around Advice

- Advice that surrounds a join point such as method invocation. - Allows custom behavior before and after the method invocation.

@Around("execution(* com.example.*(..))") public void aroundAdvice(ProceedingJoinPoint pjp) { pjp.proceed(); }

Spring Boot – AOP(Aspect Oriented Programming)

- Programming paradigm that provides modularity. - Isolates cross-cutting concerns like logging and transactions.

@Aspect public class MyAspect { }

How to Implement AOP in Spring Boot Application?

- Use AspectJ annotations. - Define pointcuts and advice.

@Aspect @Component public class LoggingAspect { @Before("execution(* com.example.*(..))") public void log() { } }

Spring AOP – Example (Spring1.2 Old Style AOP)

- Demonstrates AOP with older Spring 1.2 style.

(Old style example may vary based on specifics)

Spring AOP – AspectJ Xml Configuration

- Configure aspects using XML rather than annotations.

<aop:config> <aop:aspect ref="myAspect"> ... </aop:aspect> </aop:config>

Spring AOP – AspectJ Annotation

- Define aspects using AspectJ annotations.

@Aspect public class MyAspect { }

Usage of @Before, @After, @Around, @AfterReturning, and @AfterThrowing in a Single Spring AOP Project

- Define advices to be executed at different points in program.

@Before("pointcut()") public void before() { } @After("pointcut()") public void after() { } ...

Spring Boot – Cache Provider

- Provides caching capabilities. - Enables and configures caching in Spring Boot applications.

@EnableCaching @SpringBootApplication public class Application { }

Spring Boot – Difference Between AOP and OOP

- AOP focuses on cross-cutting concerns, OOP on defining objects and their behaviors.

N/A

Spring Boot – Difference Between AOP and AspectJ

- AOP is a paradigm, AspectJ is a Java framework implementing AOP.

N/A

Spring Boot – AOP After Throwing Advice

- Advice to be executed if method exits by throwing an exception.

@AfterThrowing(pointcut = "execution(* com.example.*(..))", throwing= "error") public void logError(Exception error) { }

Spring Boot – AOP After Returning Advice

- Advice to be executed after a method returns normally.

@AfterReturning(pointcut = "execution(* com.example.*(..))", returning= "result") public void logReturn(Object result) { }

Spring Boot – AOP After Advice

- Advice to be executed no matter method exits normally or with exception.

@After("execution(* com.example.*(..))") public void logAfter() { }

Spring Boot – AOP Before Advice

- Advice to be executed before a method invocation.

@Before("execution(* com.example.*(..))") public void logBefore() { }

Spring Security



Topic

Topic Content/Answer

JAVA Code Example

Introduction to Spring Security and its Features

- Framework for authentication and authorization in Java applications. - Provides protection against common vulnerabilities.

@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { }

Some Important Terms in Spring Security

- Authentication: Proving an identity. - Authorization: Deciding if authenticated user can access a resource. - Principal: Current user.

N/A

OAuth2 Authentication with Spring and Github

- Protocol for authorization. - Spring supports OAuth2 for authentication with third-party providers like Github.

@EnableOAuth2Sso public class OAuth2SecurityConfig extends WebSecurityConfigurerAdapter { }

Spring Security at Method Level

- Secure methods using annotations. - Restrict access to methods based on roles.

@PreAuthorize("hasRole('ADMIN')") public void adminMethod() { }

Spring Security JSP Tag Library

- Custom tags for JSPs in Spring Security. - Help display content based on user's roles.

<sec:authorize access="hasRole('ADMIN')"> Admin content here </sec:authorize>

Spring Security Form-Based Authentication

- Custom login forms. - Authenticate users based on submitted form data.

http.formLogin().loginPage("/login").permitAll();

Spring Security – Remember Me

- Allows user to stay authenticated across sessions. - Uses cookies or tokens.

http.rememberMe().key("uniqueKey").tokenValiditySeconds(86400);

Spring Security XML

- Configures Spring Security using XML rather than Java configuration.

<http auto-config="true"> <intercept-url pattern="/admin" access="ROLE_ADMIN"/> </http>

Spring Security Project Example using Java Configuration

- Demonstrates Spring Security with Java-based configuration.

@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) { ... } }

How to Change Default User and Password in Spring Security?

- Override default security properties.

spring.security.user.name=myUser spring.security.user.password=myPassword

Spring – Add Roles in Spring Security

- Define custom roles. - Assign roles to users.

auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");

Spring – Add User Name and Password in Spring Security

- Custom authentication. - Add custom users and their credentials.

auth.inMemoryAuthentication().withUser("customUser").password

Advantages of Spring



Topic

Topic Content/Answer

JAVA Code Example

Predefined Templates

- Templates in Spring provide ready-to-use functionality. - Reduce boilerplate code. - Enhance productivity by providing utility methods for database operations, JMS, etc.

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

Loose Coupling

- Spring promotes decoupled architecture. - Objects aren't tightly tied together. - Easier to manage, test, and scale the application.

@Autowired private SomeService someService;

Lightweight

- Spring framework is lightweight in terms of size and overhead. - Doesn't burden system's performance. - No need for a heavy application server.

N/A

Fast Development

- Spring reduces a lot of boilerplate code. - Dependency injection and other features speed up the development process.

@Autowired private DataSource dataSource;

Powerful abstraction

- Provides powerful abstraction for various tasks (like database operations). - Developer can focus on business logic rather than the specifics of the underlying service or API.

@Repository public class MyDAO { @Autowired private JdbcTemplate jdbcTemplate; }

Declarative support

- Supports declarative programming. - Developers can express logic without writing the actual implementation, such as transactions, logging, etc. - Uses Aspect-Oriented Programming (AOP) and other declarative approaches to separate concerns.

@Transactional public void someTransactionalMethod() { //... }


Comments

Popular posts from this blog

state government roles website

Follow these steps to install eksctl

Java Coding Interview Question and Answers 1