Last active
November 24, 2020 04:53
-
-
Save mike-neck/2a38cf3778c4b8c8a355c3b2e984f639 to your computer and use it in GitHub Desktop.
Spring AOP(MethodInterceptor)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Grab('spring-aop') | |
@Grab('aspectjrt') | |
@Grab('aspectjtools') | |
@Grab('aspectjweaver') | |
import groovy.util.logging.Slf4j | |
import java.lang.annotation.Retention | |
import java.lang.annotation.Target | |
import java.lang.annotation.RetentionPolicy | |
import java.lang.annotation.ElementType | |
import java.time.Instant | |
import java.time.format.DateTimeFormatter | |
import org.aopalliance.intercept.MethodInterceptor | |
import org.aopalliance.intercept.MethodInvocation | |
import org.springframework.web.context.request.RequestContextHolder | |
import org.springframework.web.context.request.ServletRequestAttributes | |
import org.springframework.aop.Advisor | |
import org.springframework.aop.aspectj.AspectJExpressionPointcut | |
import org.springframework.aop.support.DefaultPointcutAdvisor | |
@RestController | |
@RequestMapping('/app') | |
@Slf4j | |
class WebCon { | |
final MyService service | |
WebCon(MyService service) { this.service = service } | |
@GetMapping(produces = 'application/json') | |
ResponseEntity<Map<String,String>> get(@RequestParam(value = 'name', defaultValue = 'foo-bar') String name) { | |
log.info('get - name: {}', name) | |
return ResponseEntity.ok(name: name, now: service.now()) | |
} | |
} | |
@Component | |
class MyService { | |
@Log String now() { | |
DateTimeFormatter.ISO_INSTANT.format(Instant.now()) | |
} | |
} | |
@Component | |
@Slf4j | |
class Logging implements MethodInterceptor { | |
@Override Object invoke(MethodInvocation invocation) { | |
def attr = RequestContextHolder.currentRequestAttributes() | |
log.info('attr: {}, {}', attr.class, attr.sessionId) | |
def serv = attr as ServletRequestAttributes | |
def en = serv.request.headerNames | |
def map = [:] | |
while(en.hasMoreElements()) { | |
def k = en.nextElement() | |
map[k] = serv.request.getHeader(k) | |
} | |
log.info('header - {}', map) | |
def result = invocation.proceed() | |
log.info('{} - {}', invocation.method.name, result) | |
return result | |
} | |
} | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target(ElementType.METHOD) | |
@interface Log {} | |
@Configuration | |
class LogConfig { | |
final Logging logging | |
LogConfig(Logging logging) { this.logging = logging } | |
@Bean Advisor logAdvisor() { | |
def pointcut = new AspectJExpressionPointcut() | |
pointcut.expression = '@annotation(Log)' | |
return new DefaultPointcutAdvisor(pointcut, logging) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
running log