------------------------------------------------------------------------------------------------------------
LAB ASSIGNMENTS: Spring Boot 3.x
1. Spring boot Dependency Injection
2. Spring boot AOP
3. Spring boot REST CURD operation
4. 1. Proper ResponseEntity should be returned as per requirements
5. 2. study http status code and return appropriate status code
6. 3. Custom validation for bookType: IT, MGT
7. Spring Boot JDBCTemplate
8. Spring Boot JPA Integration
9. Spring data with mysql
10. Spring data pagination and custom quaries
11. Spring boot Logging and logging customization
12. spring boot profile
13. spring boot actuator
14. Spring boot caching (In memory)
Create BookStore application by following 3 tier architecture with following dao server layer
1. Create bookstore application
Design persistance layer:
com.training.model.persistance
public class Book {
private int id;
private String isbn;
private String title;
private String author;
private double price;
//getter setter , ctr
}
public interface BookDao {
public List<Book> getAllBooks();
public Book addBook(Book book);
public void deleteBook(int id);
public void updateBook(int id, Book book);
public Book getBookById(int id);
}
@Repository
public class BookDaoImp implements BookDao {
private static Map<Integer, Book> booksMap = new HashMap<Integer, Book>();
private static int counter = 0;
static {
booksMap.put(++counter, new Book(counter, "ABC123", "Head first Java" , "Katthy",
600));
booksMap.put(++counter, new Book(counter, "ABC723", "Servlet jsp Java" , "Katthy",
700));
}
@Override
public List<Book> getAllBooks() {
return new ArrayList<Book>(booksMap.values());
}
@Override
public Book addBook(Book book) {
book.setId(++counter);
booksMap.put(counter, book);
return booksMap.get(counter);
}
@Override
public void deleteBook(int id) {
booksMap.remove(id);
}
@Override
public void updateBook(int id, Book book) {
booksMap.put(id, book);
}
@Override
public Book getBookById(int id) {
return booksMap.get(id);
}
Design Service layer:
com.training.model.service
public interface BookService {
public List<Book> getAllBooks();
public Book addBook(Book book);
public void deleteBook(int id);
public void updateBook(int id, Book book);
public Book getBookById(int id);
}
@Service
public class BookServiceImp implements BookService {
@Autowire
private BookDao dao;
@Override
public List<Book> getAllBooks() {
return dao.getAllBooks();
}
@Override
public Book addBook(Book book) {
return dao.addBook(book);
}
@Override
public void deleteBook(int id) {
dao.deleteBook(id);
}
@Override
public void updateBook(int id, Book book) {
dao.updateBook(id, book);
}
@Override
public Book getBookById(int id) {
return dao.getBookById(id);
}
CORE SPRING: AOP
In lab DI you have created book application, now we require to log information while somebody deleted
book
Improve the application using AOP to applying logging, You can create an custom annotation such as
@Loggable and put it one deleteBook method. Now if book is deleted information about deleted book
should added to log file in aop way.
You can use code snippet mentioned below.
@Service
public interface BookService implements BookService {
@Autowire
private BookDao dao;
public List<Book> getAllBooks(){
}
public Book addBook(Book book){}
public void deleteBook(int id){
// if somebody delete book we need to log information in log file using AOP
}
public void updateBook(int id, Book book){}
public Book getBookById(int id){}
}
Custom annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Loggable {
Improve application design by AOP
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class MethodLogger {
private static final Logger logger=LoggerFactory.getLogger(MethodLogger.class);
@Around("@annotation(Loggable)")
public Object around(ProceedingJoinPoint point) throws Throwable {
long start = System.currentTimeMillis();
Object result = point.proceed();
logger.info("start "+MethodSignature.class.cast(" Method takes " +(System.currentTimeMillis() - start));
return result;
}
}
Spring REST
In this lab you need to support REST endpoint for book application.
Take the help of given code snippet. Note use of @RestController and @ RequestMapping annotation.
1. Provide support for CURD operation
2. Proper ResponseEntity should be returned as per requirments
3. study http status code and return appropiate status code
Spring REST Validation
In this lab you need to apply validation support to REST endpoint for book application.
In case validation fail user must get correct status code 400 with proper validation failure message
Validation message must not be hard coded
Spring JDBC
In lab AOP you have created book application, now we require to replace persistance layer with jdbc. Note
that service layer should
remain uneffected by the change.
@Service
public interface BookService implements BookService {
@Autowire
private BookDao dao;
public List<Book> getAllBooks(){
}
public Book addBook(Book book){}
public void deleteBook(int id){
}
public void updateBook(int id, Book book){}
public Book getBookById(int id){}
}
Implement crud method using jdbc, inject datasource in persistane layer, using xml and java configuration
Spring Hibernate/JPA
In lab Spring Jdbc you have created book application using JDBC, now we require to replace persistance
layer with Hibernate. Note that service layer should remain uneffected by the change.
@Service
public interface BookService implements BookService {
@Autowire
private SessionFactory factory;
public List<Book> getAllBooks(){
}
public Book addBook(Book book){}
public void deleteBook(int id){
}
public void updateBook(int id, Book book){}
public Book getBookById(int id){}
}
1. Implement crud method using Hibernate, inject factory in persistane layer, using xml and java
configuration
2. Implement crud method using spring-Hibernate ( reduce boilerplat code)
3. Apply declerative transaction management using @Transactinal annotation
4. Do experiments with different optionals available with @Transactinal annotation
Spring Data using MySql
In this lab you need to migrate to spring data using mysql. With spring data we dont have to write dao layer
we just need to declare dao layer
Spring data custom configuration
Spring boot is higly customized framework, although spring boot automatically configure datasource,
entitymanagerfactory etc but we can configure our bean along with transaction management, In this lab write
custom configuration of these beans
Spring boot Logging and logging customization
In this lab customized spring boot to use log4j2 and do custom logging of a specific package
spring boot profile
Profiles in Spring Boot are a way to define different sets of configurations for your application depending on
the environment it is being run in. For example, you might have one set of configurations for your
development environment and another set of configurations for your production environment
Spring boot profile help us to use different configuration depending on dev,test and prod profile, using
different database for different profile and switch profile without changing the code
spring boot actuator
Spring Boot's 'Actuator' dependency is used to monitor and manage the Spring web application. We can use
it to monitor and manage the application with the help of HTTP endpoints or with the JMX.
In this lab apply spring boot actuator and monitor application with various endpoints
Spring boot caching (In memory)
Spring Boot Caching is a feature that allows you to store data in memory so that it can be accessed more
quickly. This can improve the performance of your application by reducing the number of times that it needs
to access the database or other slow storage mechanisms.
Spring boot Schedule Process
Spring Boot Scheduler is a feature of Spring Boot that allows you to schedule tasks to be executed at a
specific time or with a certain frequency. This can be useful for automating tasks such as sending emails,
generating reports, or processing data.
Spring boot JSP Integration
Spring Boot JSP integration is a way to use JSP (JavaServer Pages) with the Spring Boot framework. JSP is a
technology that allows developers to create dynamic web pages. Spring Boot is a framework that makes it
easy to create Java applications.
To integrate JSP with Spring Boot, you need to add the following dependencies to your project:spring-boot-
starter-web, tomcat-embed-jasper, and jstl.
Spring boot RestTemplate
Spring Boot RestTemplate is a template class that simplifies the process of making HTTP requests. It
provides a number of convenience methods for making GET, POST, PUT, and DELETE requests, as well as
handling responses and exceptions
spring boot OpenFeign
Spring Cloud OpenFeign is a Java to HTTP client binder that makes it easier to write web service clients. It
was originally created and released by Netflix as Feign and then moved to the open-source community
renamed as Openfeign. Spring Cloud OpenFeign provides OpenFeign integrations for Spring Boot apps
through auto-configuration and binding to the Spring Environment.
Spring boot testing
Spring Boot provides a number of utilities and annotations to help when testing your application. Test
support is provided by two modules: spring-boot-test contains core items, and spring-boot-test-autoconfigure
supports auto-configuration for tests.
Most developers use the spring-boot-starter-test “Starter”, which imports both Spring Boot test modules as
well as JUnit, AssertJ, Hamcrest, and a number of other useful libraries.
The spring-boot-starter-test “Starter” contains the following provided libraries:
JUnit: The de-facto standard for unit testing Java applications.
Spring Test & Spring Boot Test: Utilities and integration test support for Spring Boot applications.
AssertJ: A fluent assertion library.
Hamcrest: A library of matcher objects (also known as constraints or predicates).
Mockito: A Java mocking framework.
JSONassert: An assertion library for JSON.
JsonPath: XPath for JSON.
Spring boot jacoco code coverage
Upon completing the writing of Unit Testing, it is essential to see how much the tests covered the code and
identify areas that require additional testing. We do those things to make sure the application code is
thoroughly tested and ready for deployment. Today I will introduce JaCoCo, a tool for generating code
coverage reports for Java projects.
spring boot sonarqube
SonarQube is an open-source platform for continuous inspection of code quality. It performs automated code
analysis and provides detailed reports on code quality, code coverage, and various code-related issues,
including bugs, vulnerabilities, and code smells. Integrating SonarQube into a Spring project can help you
maintain high code quality and detect issues early in the development process
Spring boot RestTemplate, OpenFeign
RestTemplate is a class in Spring that allows for client-side HTTP access.
It's a synchronous client that uses the Java.net.HttpURLConnection HTTP client library to
make RESTful requests to external APIs and services. RestTemplate provides templates for common
scenarios by HTTP method, as well as generalized exchange and execute methods for less frequent cases. It
also has methods for making GET, POST, PUT, and DELETE requests, as well as the ability to handle
exceptions and responses.
OpenFeign is a declarative web service client. It makes writing web service clients easier. When calling
other services using Feign, we don't need to write any code. We just need to create an interface and annotate
it. It has support for OpenFeign and Jakarta JAX-RS annotations.
Spring boot RabbitMQ integration
RabbitMQ is an open-source messaging broker that allows communication between different software
systems, services, and devices. It uses the Advanced Message Queuing Protocol (AMQP), a standardized
communication protocol for scalable messaging. RabbitMQ is made up of broker processes that host
exchanges for publishing messages and queues for consuming messages. It's often compared to a post office
for applications and messages.
Spring boot Kafka integration
Apache Kafka is an open-source, distributed streaming platform that allows applications to publish,
subscribe to, store, and process streams of records in real time. It's used to build real-time streaming data
pipelines and applications. Kafka can handle data streams from multiple sources and deliver them to multiple
consumers, and can reduce latency to milliseconds
Spring security basics Auth
Spring Security is a framework which provides various security features like: authentication, authorization to
create secure Java Enterprise Applications.Spring Security is a framework which provides various security
features like: authentication, authorization to create secure Java Enterprise Applications.
Spring Security JWT Integration
JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between two
parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs
can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
Although JWTs can be used for more than authentication, this is their primary use. Because they are digitally
signed, they can be used to verify the identity of the issuer.