Skip to content

Commit 9f22bed

Browse files
author
Ramesh Fadatare
committed
added spring aop examples and tutorials
1 parent 4a3ebdf commit 9f22bed

File tree

32 files changed

+1200
-0
lines changed

32 files changed

+1200
-0
lines changed

spring-aop-advice-examples/.gitignore

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/target/
2+
!.mvn/wrapper/maven-wrapper.jar
3+
4+
### STS ###
5+
.apt_generated
6+
.classpath
7+
.factorypath
8+
.project
9+
.settings
10+
.springBeans
11+
.sts4-cache
12+
13+
### IntelliJ IDEA ###
14+
.idea
15+
*.iws
16+
*.iml
17+
*.ipr
18+
19+
### NetBeans ###
20+
/nbproject/private/
21+
/build/
22+
/nbbuild/
23+
/dist/
24+
/nbdist/
25+
/.nb-gradle/
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip

spring-aop-advice-examples/pom.xml

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>net.guides.springboot2</groupId>
8+
<artifactId>springboot2-springaop-example</artifactId>
9+
<version>0.0.1-SNAPSHOT</version>
10+
<packaging>jar</packaging>
11+
12+
<name>springboot2-springaop-example</name>
13+
<description>Demo project for Spring Boot</description>
14+
15+
<parent>
16+
<groupId>org.springframework.boot</groupId>
17+
<artifactId>spring-boot-starter-parent</artifactId>
18+
<version>2.1.4.RELEASE</version>
19+
<relativePath /> <!-- lookup parent from repository -->
20+
</parent>
21+
22+
<properties>
23+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
24+
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
25+
<java.version>1.8</java.version>
26+
</properties>
27+
28+
<dependencies>
29+
<dependency>
30+
<groupId>org.springframework.boot</groupId>
31+
<artifactId>spring-boot-starter-data-jpa</artifactId>
32+
</dependency>
33+
<dependency>
34+
<groupId>org.springframework.boot</groupId>
35+
<artifactId>spring-boot-starter-web</artifactId>
36+
</dependency>
37+
38+
<dependency>
39+
<groupId>org.springframework.boot</groupId>
40+
<artifactId>spring-boot-starter-actuator</artifactId>
41+
</dependency>
42+
43+
<dependency>
44+
<groupId>org.springframework.boot</groupId>
45+
<artifactId>spring-boot-starter-aop</artifactId>
46+
</dependency>
47+
48+
<dependency>
49+
<groupId>org.springframework.boot</groupId>
50+
<artifactId>spring-boot-devtools</artifactId>
51+
<scope>runtime</scope>
52+
</dependency>
53+
<dependency>
54+
<groupId>com.h2database</groupId>
55+
<artifactId>h2</artifactId>
56+
<scope>runtime</scope>
57+
</dependency>
58+
<dependency>
59+
<groupId>org.springframework.boot</groupId>
60+
<artifactId>spring-boot-starter-test</artifactId>
61+
<scope>test</scope>
62+
</dependency>
63+
</dependencies>
64+
65+
<build>
66+
<plugins>
67+
<plugin>
68+
<groupId>org.springframework.boot</groupId>
69+
<artifactId>spring-boot-maven-plugin</artifactId>
70+
</plugin>
71+
</plugins>
72+
</build>
73+
74+
75+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package net.guides.springboot2.springboot2jpacrudexample;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
import org.springframework.boot.web.client.RestTemplateBuilder;
6+
import org.springframework.context.annotation.Bean;
7+
import org.springframework.web.client.RestTemplate;
8+
9+
@SpringBootApplication
10+
public class Application {
11+
12+
@Bean
13+
public RestTemplate restTemplate(RestTemplateBuilder builder) {
14+
return builder.build();
15+
}
16+
17+
public static void main(String[] args) {
18+
SpringApplication.run(Application.class, args);
19+
}
20+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package net.guides.springboot2.springboot2jpacrudexample;
2+
3+
import java.util.Arrays;
4+
import java.util.HashMap;
5+
import java.util.Map;
6+
7+
import org.springframework.http.HttpEntity;
8+
import org.springframework.http.HttpHeaders;
9+
import org.springframework.http.HttpMethod;
10+
import org.springframework.http.MediaType;
11+
import org.springframework.http.ResponseEntity;
12+
import org.springframework.web.client.RestTemplate;
13+
14+
import net.guides.springboot2.springboot2jpacrudexample.model.Employee;
15+
16+
public class SpringRestClient {
17+
18+
private static final String GET_EMPLOYEES_ENDPOINT_URL = "http://localhost:8080/api/v1/employees";
19+
private static final String GET_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees/{id}";
20+
private static final String CREATE_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees";
21+
private static final String UPDATE_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees/{id}";
22+
private static final String DELETE_EMPLOYEE_ENDPOINT_URL = "http://localhost:8080/api/v1/employees/{id}";
23+
private static RestTemplate restTemplate = new RestTemplate();
24+
25+
public static void main(String[] args) {
26+
SpringRestClient springRestClient = new SpringRestClient();
27+
28+
// Step1: first create a new employee
29+
springRestClient.createEmployee();
30+
31+
// Step 2: get new created employee from step1
32+
springRestClient.getEmployeeById();
33+
34+
// Step3: get all employees
35+
springRestClient.getEmployees();
36+
37+
// Step4: Update employee with id = 1
38+
springRestClient.updateEmployee();
39+
40+
// Step5: Delete employee with id = 1
41+
springRestClient.deleteEmployee();
42+
}
43+
44+
private void getEmployees() {
45+
46+
HttpHeaders headers = new HttpHeaders();
47+
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
48+
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
49+
50+
ResponseEntity<String> result = restTemplate.exchange(GET_EMPLOYEES_ENDPOINT_URL, HttpMethod.GET, entity,
51+
String.class);
52+
53+
System.out.println(result);
54+
}
55+
56+
private void getEmployeeById() {
57+
58+
Map<String, String> params = new HashMap<String, String>();
59+
params.put("id", "1");
60+
61+
RestTemplate restTemplate = new RestTemplate();
62+
Employee result = restTemplate.getForObject(GET_EMPLOYEE_ENDPOINT_URL, Employee.class, params);
63+
64+
System.out.println(result);
65+
}
66+
67+
private void createEmployee() {
68+
69+
Employee newEmployee = new Employee("admin", "admin", "[email protected]");
70+
71+
RestTemplate restTemplate = new RestTemplate();
72+
Employee result = restTemplate.postForObject(CREATE_EMPLOYEE_ENDPOINT_URL, newEmployee, Employee.class);
73+
74+
System.out.println(result);
75+
}
76+
77+
private void updateEmployee() {
78+
Map<String, String> params = new HashMap<String, String>();
79+
params.put("id", "1");
80+
Employee updatedEmployee = new Employee("admin123", "admin123", "[email protected]");
81+
RestTemplate restTemplate = new RestTemplate();
82+
restTemplate.put(UPDATE_EMPLOYEE_ENDPOINT_URL, updatedEmployee, params);
83+
}
84+
85+
private void deleteEmployee() {
86+
Map<String, String> params = new HashMap<String, String>();
87+
params.put("id", "1");
88+
RestTemplate restTemplate = new RestTemplate();
89+
restTemplate.delete(DELETE_EMPLOYEE_ENDPOINT_URL, params);
90+
}
91+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
package net.guides.springboot2.springboot2jpacrudexample.aspect;
2+
3+
import java.util.Arrays;
4+
5+
import org.aspectj.lang.JoinPoint;
6+
import org.aspectj.lang.ProceedingJoinPoint;
7+
import org.aspectj.lang.annotation.After;
8+
import org.aspectj.lang.annotation.AfterReturning;
9+
import org.aspectj.lang.annotation.AfterThrowing;
10+
import org.aspectj.lang.annotation.Around;
11+
import org.aspectj.lang.annotation.Aspect;
12+
import org.aspectj.lang.annotation.Before;
13+
import org.slf4j.Logger;
14+
import org.slf4j.LoggerFactory;
15+
import org.springframework.stereotype.Component;
16+
17+
/**
18+
* Aspect for logging execution.
19+
*
20+
* @author Ramesh Fadatare
21+
*
22+
*/
23+
@Aspect
24+
@Component
25+
public class LoggingAspect {
26+
27+
private final Logger log = LoggerFactory.getLogger(this.getClass());
28+
29+
/**
30+
* Run before the method execution.
31+
* @param joinPoint
32+
*/
33+
@Before("execution(* net.guides.springboot2.springboot2jpacrudexample.service.EmployeeService.addEmployee(..))")
34+
public void logBefore(JoinPoint joinPoint) {
35+
log.debug("logBefore running .....");
36+
log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
37+
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
38+
39+
}
40+
41+
/**
42+
* Run after the method returned a result.
43+
* @param joinPoint
44+
*/
45+
@After("execution(* net.guides.springboot2.springboot2jpacrudexample.service.EmployeeService.addEmployee(..))")
46+
public void logAfter(JoinPoint joinPoint) {
47+
log.debug("logAfter running .....");
48+
log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
49+
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
50+
}
51+
52+
/**
53+
* Run after the method returned a result, intercept the returned result as well.
54+
* @param joinPoint
55+
* @param result
56+
*/
57+
@AfterReturning(pointcut = "execution(* net.guides.springboot2.springboot2jpacrudexample.service.EmployeeService.deleteEmployee(..))", returning = "result")
58+
public void logAfterReturning(JoinPoint joinPoint, Object result) {
59+
log.debug("logAfterReturning running .....");
60+
log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
61+
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
62+
63+
}
64+
65+
/**
66+
* Run around the method execution.
67+
* @param joinPoint
68+
* @return
69+
* @throws Throwable
70+
*/
71+
@Around("execution(* net.guides.springboot2.springboot2jpacrudexample.service.EmployeeService.getEmployeeById(..))")
72+
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
73+
log.debug("logAround running .....");
74+
if (log.isDebugEnabled()) {
75+
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
76+
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
77+
}
78+
try {
79+
Object result = joinPoint.proceed();
80+
if (log.isDebugEnabled()) {
81+
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
82+
joinPoint.getSignature().getName(), result);
83+
}
84+
return result;
85+
} catch (IllegalArgumentException e) {
86+
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
87+
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
88+
throw e;
89+
}
90+
91+
}
92+
93+
/**
94+
* Advice that logs methods throwing exceptions.
95+
*
96+
* @param joinPoint join point for advice
97+
* @param e exception
98+
*/
99+
100+
@AfterThrowing(pointcut = "execution(* net.guides.springboot2.springboot2jpacrudexample.service.EmployeeService.updateEmployee(..))", throwing = "error")
101+
public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {
102+
log.debug("logAfterThrowing running .....");
103+
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
104+
joinPoint.getSignature().getName(), error.getCause() != null ? error.getCause() : "NULL");
105+
}
106+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package net.guides.springboot2.springboot2jpacrudexample.controller;
2+
3+
import java.util.List;
4+
import java.util.Map;
5+
6+
import javax.validation.Valid;
7+
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.http.ResponseEntity;
10+
import org.springframework.web.bind.annotation.DeleteMapping;
11+
import org.springframework.web.bind.annotation.GetMapping;
12+
import org.springframework.web.bind.annotation.PathVariable;
13+
import org.springframework.web.bind.annotation.PostMapping;
14+
import org.springframework.web.bind.annotation.PutMapping;
15+
import org.springframework.web.bind.annotation.RequestBody;
16+
import org.springframework.web.bind.annotation.RequestMapping;
17+
import org.springframework.web.bind.annotation.RestController;
18+
19+
import net.guides.springboot2.springboot2jpacrudexample.exception.ResourceNotFoundException;
20+
import net.guides.springboot2.springboot2jpacrudexample.model.Employee;
21+
import net.guides.springboot2.springboot2jpacrudexample.service.EmployeeService;
22+
23+
@RestController
24+
@RequestMapping("/api/v1")
25+
public class EmployeeController {
26+
@Autowired
27+
private EmployeeService employeeService;
28+
29+
@GetMapping("/employees")
30+
public List<Employee> getAllEmployees() {
31+
return employeeService.getAllEmployees();
32+
}
33+
34+
@GetMapping("/employees/{id}")
35+
public ResponseEntity<Employee> getEmployeeById(@PathVariable(value = "id") Long employeeId)
36+
throws ResourceNotFoundException {
37+
Employee employee = employeeService.getEmployeeById(employeeId)
38+
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
39+
return ResponseEntity.ok().body(employee);
40+
}
41+
42+
@PostMapping("/employees")
43+
public Employee createEmployee(@Valid @RequestBody Employee employee) {
44+
return employeeService.addEmployee(employee);
45+
}
46+
47+
@PutMapping("/employees/{id}")
48+
public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long employeeId,
49+
@Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
50+
Employee updatedEmployee = employeeService.updateEmployee(employeeId, employeeDetails);
51+
return ResponseEntity.ok(updatedEmployee);
52+
}
53+
54+
@DeleteMapping("/employees/{id}")
55+
public Map<String, Boolean> deleteEmployee(@PathVariable(value = "id") Long employeeId)
56+
throws ResourceNotFoundException {
57+
return employeeService.deleteEmployee(employeeId);
58+
}
59+
}

0 commit comments

Comments
 (0)