Рубрики
Без рубрики

Пример аннотации Spring AOP + AspectJ

– Пример аннотации Spring AOP + AspectJ

В этом уроке мы покажем вам, как интегрировать аннотацию AspectJ с платформой Spring AOP. Проще говоря, Spring AOP + AspectJ позволяют легко перехватывать метод.

Общие аннотации AspectJ:

  1. @До – Запуск перед выполнением метода
  2. @After – Запуск после того, как метод вернул результат
  3. @AfterReturning – Запуск после того, как метод вернул результат, также перехватите возвращенный результат.
  4. @Послесловие – Запуск после того, как метод выдаст исключение
  5. @Вокруг – Обегите выполнение метода, объедините все три совета выше.

1. Структура каталогов

См. Структуру каталогов в этом примере.

2. Зависимости проекта

Чтобы включить AspectJ, вам нужно aspectjrt.jar , aspectjweaver.jar и spring-aop.jar . Смотрите следующий Maven pom.xml файл.

Файл: pom.xml



	
		3.0.5.RELEASE
	

	

		
			org.springframework
			spring-core
			${spring.version}
		

		
			org.springframework
			spring-context
			${spring.version}
		

		
		
			org.springframework
			spring-aop
			${spring.version}
		

		
			org.aspectj
			aspectjrt
			1.6.11
		
		
		
			org.aspectj
			aspectjweaver
			1.6.11
		
		
	

3. Весенние Бобы

Обычный компонент, с несколькими методами, позже перехватит его с помощью аннотации AspectJ.

package com.mkyong.customer.bo;

public interface CustomerBo {

	void addCustomer();
	
	String addCustomerReturnValue();
	
	void addCustomerThrowException() throws Exception;
	
	void addCustomerAround(String name);
}
package com.mkyong.customer.bo.impl;

import com.mkyong.customer.bo.CustomerBo;

public class CustomerBoImpl implements CustomerBo {

	public void addCustomer(){
		System.out.println("addCustomer() is running ");
	}
	
	public String addCustomerReturnValue(){
		System.out.println("addCustomerReturnValue() is running ");
		return "abc";
	}
	
	public void addCustomerThrowException() throws Exception {
		System.out.println("addCustomerThrowException() is running ");
		throw new Exception("Generic Error");
	}
	
	public void addCustomerAround(String name){
		System.out.println("addCustomerAround() is running, args : " + name);
	}
}

4. Включить АспектJ

В файле конфигурации Spring поместите ” ” и определите свой аспект (перехватчик) и обычный компонент.

Файл: Spring-Customer.xml



	

	

	
	


4. Аспект j @Раньше

В приведенном ниже примере метод log Before() будет выполнен до выполнения пользовательского интерфейса, AddCustomer() метод.

Файл: LoggingAspect.java

package com.mkyong.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {

	@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
	public void logBefore(JoinPoint joinPoint) {

		System.out.println("logBefore() is running!");
		System.out.println("hijacked : " + joinPoint.getSignature().getName());
		System.out.println("******");
	}

}

Запустите его

	CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
	customer.addCustomer();

Выход

logBefore() is running!
hijacked : addCustomer
******
addCustomer() is running 

5. Аспект j @После

В приведенном ниже примере метод log After() будет выполнен после выполнения пользовательского интерфейса, AddCustomer() метод.

Файл: LoggingAspect.java

package com.mkyong.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;

@Aspect
public class LoggingAspect {

	@After("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
	public void logAfter(JoinPoint joinPoint) {

		System.out.println("logAfter() is running!");
		System.out.println("hijacked : " + joinPoint.getSignature().getName());
		System.out.println("******");

	}

}

Запустите его

	CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
	customer.addCustomer();

Выход

addCustomer() is running 
logAfter() is running!
hijacked : addCustomer
******

6. Аспект j @После возвращения

В приведенном ниже примере метод logafterreturning() будет выполнен после выполнения пользовательского интерфейса, addCustomerReturnValue() метод. Кроме того, вы можете перехватить возвращаемое значение с помощью атрибута ” returning “.

Чтобы перехватить возвращаемое значение, значение атрибута “возвращаемый” (результат) должно совпадать с параметром метода (результат).

Файл: LoggingAspect.java

package com.mkyong.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;

@Aspect
public class LoggingAspect {

   @AfterReturning(
      pointcut = "execution(* com.mkyong.customer.bo.CustomerBo.addCustomerReturnValue(..))",
      returning= "result")
   public void logAfterReturning(JoinPoint joinPoint, Object result) {

	System.out.println("logAfterReturning() is running!");
	System.out.println("hijacked : " + joinPoint.getSignature().getName());
	System.out.println("Method returned value is : " + result);
	System.out.println("******");

   }

}

Запустите его

	CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
	customer.addCustomerReturnValue();

Выход

addCustomerReturnValue() is running 
logAfterReturning() is running!
hijacked : addCustomerReturnValue
Method returned value is : abc
******

7. Аспект j @После возвращения

В приведенном ниже примере метод logAfterThrowing() будет выполнен, если пользовательский интерфейс, метод add Customer Throw-исключение() создает исключение.

Файл: LoggingAspect.java

package com.mkyong.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;

@Aspect
public class LoggingAspect {

   @AfterThrowing(
      pointcut = "execution(* com.mkyong.customer.bo.CustomerBo.addCustomerThrowException(..))",
      throwing= "error")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {

	System.out.println("logAfterThrowing() is running!");
	System.out.println("hijacked : " + joinPoint.getSignature().getName());
	System.out.println("Exception : " + error);
	System.out.println("******");

    }
}

Запустите его

	CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
	customer.addCustomerThrowException();

Выход

addCustomerThrowException() is running 
logAfterThrowing() is running!
hijacked : addCustomerThrowException
Exception : java.lang.Exception: Generic Error
******
Exception in thread "main" java.lang.Exception: Generic Error
	//...

8. Аспект j @Вокруг

В приведенном ниже примере метод log Around() будет выполнен перед пользовательским интерфейсом, Метод addCustomerAround() , и вы должны определить ” joinpoint.proceed(); “, чтобы контролировать, когда перехватчик должен вернуть элемент управления в исходное Метод addCustomerAround() .

Файл: LoggingAspect.java

package com.mkyong.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;

@Aspect
public class LoggingAspect {

   @Around("execution(* com.mkyong.customer.bo.CustomerBo.addCustomerAround(..))")
   public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {

	System.out.println("logAround() is running!");
	System.out.println("hijacked method : " + joinPoint.getSignature().getName());
	System.out.println("hijacked arguments : " + Arrays.toString(joinPoint.getArgs()));
		
	System.out.println("Around before is running!");
	joinPoint.proceed(); //continue on the intercepted method
	System.out.println("Around after is running!");
		
	System.out.println("******");

   }
	
}

Запустите его

	CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
	customer.addCustomerAround("mkyong");

Выход

logAround() is running!
hijacked method : addCustomerAround
hijacked arguments : [mkyong]
Around before is running!
addCustomerAround() is running, args : mkyong
Around after is running!
******

Вывод

Всегда рекомендуется применять аннотацию с наименьшей мощностью Aspectj. Это довольно длинная статья о AspectJ весной. для получения дополнительных пояснений и примеров, пожалуйста, посетите ссылки ниже.

Скачать Исходный Код

Рекомендации

  1. Руководство по программированию AspectJ
  2. Ссылка на Spring AOP + AspectJ

Оригинал: “https://mkyong.com/spring3/spring-aop-aspectj-annotation-example/”