Spring – 28 – Aspect Oriented Programming (AOP) – 02

Merhaba Arkadaslar
Bu bolumde Spring AOP ile ilgili ornek basit uygulamalar gerceklestirecegiz.

Spring AOP yaklasimi farkli sekillerde uygulanmaktadir.
Spring ‘in eski versiyonlarindan beri desteklenen yaklasim olarak ilgili interface’leri implements edebiliriz.

  • MethodBeforeAdvice
  • AfterReturningAdvice
  • MethodInterceptor
  • ThrowsAdvice

advicehierarchy

MethodBeforeAdvice

Orneklerimizde kullanacagimiz , output olarak basit bir mesaj basan metodu tanimlayalim ;

LoggerWriter.java

package _33.spring.aop.service;

public class LoggerWriter {
	public void log() {
		System.out.println("This is log method ! ");
	}
}

SimpleBeforeAdviceImpl.java
MethodBeforeAdvice arabirimini(interface) uygulayalim (implements).
before metodunu override edelim.

package _33.spring.aop.service;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class SimpleBeforeAdviceImpl implements MethodBeforeAdvice {

	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
		System.out.println("Before method: " + method.getName());
	}

}

SimpleBeforeAdviceTest.java

package _33.spring.aop.test;

import org.springframework.aop.framework.ProxyFactory;
import _33.spring.aop.service.LoggerWriter;
import _33.spring.aop.service.SimpleBeforeAdviceImpl;

public class SimpleBeforeAdviceTest {
	public static void main(String[] args) {

		LoggerWriter target = new LoggerWriter();
		ProxyFactory pf = new ProxyFactory();
		pf.addAdvice(new SimpleBeforeAdviceImpl());
		pf.setTarget(target);
		LoggerWriter proxy = (LoggerWriter) pf.getProxy();
		proxy.log();
	}

}

Target object ; LoggerWriter
ProxyFactory object’ini olusturduk. SimpleBeforeAdviceImpl instance’ini advice olarak addAdvice metoduna veriyoruz.
setTarget metoduna target objemizi veriyoruz.
getProxy metodumuz araciligiyla LoggerWriter objemizi olusturuyoruz.

log metodumuzu calistirdigimizda oncesinde before metodu calisacaktir.

Ornegimizi calistirdigimizda ;

Before method: log
This is log method ! 

AfterReturningAdvice

SimpleAfterReturningAdviceImpl.java

AfterReturningAdvice arabirimini(interface) uygulayalim (implements).
afterReturning metodunu override edelim.

package _33.spring.aop.service;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;

public class SimpleAfterReturningAdviceImpl implements AfterReturningAdvice {

	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		System.out.println("After method: " + method.getName());
	}
}

SimpleAfterReturningAdviceTest.java

package _33.spring.aop.test;

import org.springframework.aop.framework.ProxyFactory;
import _33.spring.aop.service.LoggerWriter;
import _33.spring.aop.service.SimpleAfterReturningAdviceImpl;

public class SimpleAfterReturningAdviceTest {
	public static void main(String[] args) {

		LoggerWriter target = new LoggerWriter();
		ProxyFactory pf = new ProxyFactory();
		pf.addAdvice(new SimpleAfterReturningAdviceImpl());
		pf.setTarget(target);
		LoggerWriter proxy = (LoggerWriter) pf.getProxy();
		proxy.log();
	}

}

log metodumuzu calistirdigimizda sonrasinda afterReturning metodu calisacaktir.

This is log method ! 
After method: log

AroundAdvice

SimpleAroundAdviceImpl.java

MethodInterceptor arabirimini(interface) uygulayalim (implements).
invoke metodunu override edelim.

package _33.spring.aop.service;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class SimpleAroundAdviceImpl implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		System.out.println("Before !");
		Object retVal = invocation.proceed();
		System.out.println("After ! ");
		return retVal;
	}

}

SimpleAroundAdviceTest.java

package _33.spring.aop.test;

import org.springframework.aop.framework.ProxyFactory;
import _33.spring.aop.service.LoggerWriter;
import _33.spring.aop.service.SimpleAroundAdviceImpl;

public class SimpleAroundAdviceTest {
	public static void main(String[] args) {

		LoggerWriter target = new LoggerWriter();
		ProxyFactory pf = new ProxyFactory();
		pf.addAdvice(new SimpleAroundAdviceImpl());
		pf.setTarget(target);		
		LoggerWriter proxy = (LoggerWriter) pf.getProxy();
		proxy.log();
	}
}

log metodumuzu calistirdigimizda oncesinde invoke metodu calisacaktir.
invocation.proceed() metodunu cagirdigimizda log metodu calisacaktir sonrasinda invoke metodu calismasina kaldigi yerden devam edecektir.

Before !
This is log method ! 
After ! 

Throws Advice

Bir diger Advice type olarak ThrowsAdvice ‘i inceleyecegiz.
Basit bir validasyon sinifi yazalim.

Validator.java

package _33.spring.aop.service;

public class Validator {
	public void validateAge(int age) throws Exception {
		if (age < 0) {
			throw new ArithmeticException("Not Valid Age");
		} else {
			System.out.println("It is valid age!");
		}
	}

	public int parseAge(String age) {
		return Integer.parseInt(age);
	}

	public void throwRuntimeException() {
		throw new RuntimeException();
	}
}

SimpleThrowsAdviceImpl.java

ThrowsAdvice arabiriminde tanimli bir metot yer almamaktadir.
Fakat ilgili metotlar su formatta tanimli oldugunda reflection vasitasiyla metotlar ilgili exception durumunda calistirilacaktir.

void afterThrowing([Method, args, target], ThrowableSubclass);
Some examples of valid methods would be:

public void afterThrowing(Exception ex)
public void afterThrowing(RemoteException)
public void afterThrowing(Method method, Object[] args, Object target, Exception ex)
public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)
package _33.spring.aop.service;

import java.lang.reflect.Method;

import org.springframework.aop.ThrowsAdvice;

public class SimpleThrowsAdviceImpl implements ThrowsAdvice {
		
	public void afterThrowing(Exception ex) throws Throwable {
		System.out.println("***");
		System.out.println("Generic Exception Capture");
		System.out.println("Caught: " + ex.getClass().getName());
		System.out.println("***");
	}


	public void afterThrowing(Method method, Object[] args, Object target, ArithmeticException ex)
			throws Throwable {
		System.out.println("***");
		System.out.println("ArithmeticException Capture");
		System.out.println("Caught: " + ex.getClass().getName());
		System.out.println("Method: " + method.getName());
		System.out.println("***");
	}
	
	public void afterThrowing(Method method, Object[] args, Object target, NumberFormatException ex)
			throws Throwable {
		System.out.println("***");
		System.out.println("NumberFormatException Capture");
		System.out.println("Caught: " + ex.getClass().getName());
		System.out.println("Method: " + method.getName());
		System.out.println("***");
	}
}

SimpleThrowsAdviceTest.java

validateAge metoduna negatif deger verdigimizde ArithmeticException firlatacaktir. Bu noktada ilgili afterThrowing metodu calisacaktir.
Benzer sekilde parseAge metodu da NumberFormatException firlatacaktir.
Son olarak throwRuntimeException da RuntimeException firlatacaktir.

package _33.spring.aop.test;

import org.springframework.aop.framework.ProxyFactory;

import _33.spring.aop.service.SimpleThrowsAdviceImpl;
import _33.spring.aop.service.Validator;

public class SimpleThrowsAdviceTest {
	public static void main(String[] args) throws Exception {
		Validator errorBean = new Validator();

		ProxyFactory pf = new ProxyFactory();
		pf.setTarget(errorBean);
		pf.addAdvice(new SimpleThrowsAdviceImpl());
		Validator validator = (Validator) pf.getProxy();

		try {
			validator.validateAge(-10);
		} catch (ArithmeticException e) {
			System.out.println("ArithmeticException#catch\n");
		}

		try {
			validator.parseAge("Exception");
		} catch (NumberFormatException e) {
			System.out.println("NumberFormatException#catch\n");
		}
	
		try {
		        validator.throwRuntimeException();
		} catch (RuntimeException e) {
			System.out.println("RuntimeException#catch\n");
		}
	}

}

Ornegimizi calistirdigimizda ;

***
ArithmeticException Capture
Caught: java.lang.ArithmeticException
Method: validateAge
***
ArithmeticException#catch

***
NumberFormatException Capture
Caught: java.lang.NumberFormatException
Method: parseAge
***
NumberFormatException#catch

***
Generic Exception Capture
Caught: java.lang.RuntimeException
***
RuntimeException#catch


Github kaynak dosyalar/ source folder
leventerguder/injavawetrust-spring-tutorial

Yazimi burada sonlandiriyorum.
Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
OCP, Java SE 6 Programmer
OCE, Java EE 6 Web Component Developer

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *