Skip to content

Commit

Permalink
Add dependency injection to the AspectJ interceptor
Browse files Browse the repository at this point in the history
  • Loading branch information
kasramp committed May 11, 2020
1 parent ba763c9 commit 5c48872
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 6 deletions.
@@ -1,22 +1,21 @@
package com.madadipouya.sample.aspectj.interceptor;

import com.madadipouya.sample.aspectj.service.LoggingService;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.ZoneOffset;
import java.time.ZonedDateTime;

@Aspect
@Component
public class LoggingInterceptor {

private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);
@Autowired
private LoggingService loggingService;

@Before(value = "execution(* com.madadipouya.sample.aspectj.controller.UserController.getUsersInternal(..))")
public void addCommandDetailsToMessage() throws Throwable {
logger.info("User controller getUsers method called at {}", ZonedDateTime.now(ZoneOffset.UTC));
loggingService.log(String.format("User controller getUsers method called at %s", ZonedDateTime.now((ZoneOffset.UTC))));
}
}
@@ -0,0 +1,15 @@
package com.madadipouya.sample.aspectj.interceptor.config;

import com.madadipouya.sample.aspectj.interceptor.LoggingInterceptor;
import org.aspectj.lang.Aspects;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class LoggingInterceptorConfig {

@Bean
public LoggingInterceptor getAutowireCapableLoggingInterceptor() {
return Aspects.aspectOf(LoggingInterceptor.class);
}
}
@@ -0,0 +1,6 @@
package com.madadipouya.sample.aspectj.service;

public interface LoggingService {

void log(String message);
}
@@ -0,0 +1,22 @@
package com.madadipouya.sample.aspectj.service.impl;

import com.madadipouya.sample.aspectj.service.LoggingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
* A dummy implementation of logging service,
* just to inject it in {@link com.madadipouya.sample.aspectj.interceptor.LoggingInterceptor}
* that's managed by AspectJ
*/
@Service
public class DefaultLoggingService implements LoggingService {

private static final Logger logger = LoggerFactory.getLogger("sample-spring-aspectj");

@Override
public void log(String message) {
logger.info(message);
}
}

0 comments on commit 5c48872

Please sign in to comment.