kratos2333
1/29/2017 - 12:54 AM

Aspect for the annotation

Aspect for the annotation

package com.ewolff.aspect;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.ewolff.aspect.TraceAnnotationAspect;
import com.ewolff.configuration.SystemConfiguration;
import com.ewolff.service.SimpleService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SystemConfiguration.class)
public class TraceAnnotationAspectTest {

	@Autowired
	TraceAnnotationAspect traceAnnotationAspect;

	@Autowired
	SimpleService simpleService;

	@Before
	public void setUp() {
		traceAnnotationAspect.resetCalled();
	}

	@Test
	public void tracingOnNotAnnotatedMethodIsNotCalled() {
		assertThat(traceAnnotationAspect.getCalled(), is(0));
		simpleService.doSomething();
		assertThat(traceAnnotationAspect.getCalled(), is(0));
	}

	@Test
	public void tracingOnAnnotatedMethodIsCalled() {
		assertThat(traceAnnotationAspect.getCalled(), is(0));
		simpleService.annotated();
		assertThat(traceAnnotationAspect.getCalled(), is(1));
	}

}
package com.ewolff.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class TraceAnnotationAspect {
	
	Logger logger = LoggerFactory.getLogger(TraceAnnotationAspect.class);
	private int called=0;

	@Around("execution(@annotation.Trace * *(..))")
	public void trace(ProceedingJoinPoint proceedingJP ) throws Throwable {
		String methodInformation = 
				proceedingJP.getStaticPart().getSignature().getName();
		logger.trace("Entering "+methodInformation);
		called++;
		try {
			proceedingJP.proceed();
		} catch (Throwable ex) {
			logger.error("Exception in "+methodInformation, ex);
			throw ex;
		} finally {
			logger.trace("Exiting "+methodInformation);
		}
	}

	public void resetCalled() {
		called=0;
	}
	
	public int getCalled() {
		return called;
	}

}
package annotation;

public @interface Trace {

}
package com.ewolff.service;

import org.springframework.stereotype.Service;

import annotation.Trace;

@Service
public class SimpleService {

  public void doSomething() {
  }

  @Trace
  public void annotated() {
  }
}