KEMBAR78
Assignment 1-Spring AOP | PDF
0% found this document useful (0 votes)
7 views2 pages

Assignment 1-Spring AOP

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

Assignment 1-Spring AOP

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

Assignment 1: Spring Boot AOP (Aspect

Oriented Programming)
Objective

To understand how Spring AOP works by creating a simple application that logs method
execution time using an Aspect.

Part 1: Setup
1. Create a new Spring Boot project (via https://start.spring.io/).
o Dependencies:
▪ Spring Web
▪ Spring AOP

Part 2: Create a Service


1. Create a class BookService with methods:
2. public void addBook(String title) {
3. System.out.println("Book added: " + title);
4. }
5.
6. public void getBookById(Long id) {
7. System.out.println("Fetching book with id: " + id);
8. }

Part 3: Create an Aspect


1. Create a class LoggingAspect with annotations:
o @Aspect
o @Component
2. Add advice methods:
o @Before → log before method runs
o @After → log after method runs
o @Around → measure execution time

Example:

@Before("execution(* com.example.demo.service.BookService.*(..))")
public void logBefore(JoinPoint joinPoint) {
// - - - -- ---

Part 4: Test with CommandLineRunner


1. In the main application class, use a CommandLineRunner bean:
2. @Bean
3. CommandLineRunner run(BookService bookService) {
4. return args -> {
5. bookService.addBook("Spring in Action");
6. bookService.getBookById(101L);
7. };
8. }

Expected Output (in Console)


Before Method: addBook
Book added: Spring in Action
After Method: addBook
Before Method: getBookById
Fetching book with id: 101
After Method: getBookById

Outcome:
Learners will see how AOP intercepts method calls and adds cross-cutting concerns (logging)
without modifying the actual service logic.

You might also like