Spring AOP start close connection con anotaciones

package net.prietopalacios.josemanuel.aop.service;

public interface Service {

	public void sendSomething();
	public void sendEsception() throws Exception;
	
}
package net.prietopalacios.josemanuel.aop.service;


public class ServiceImpl implements Service {

	public void sendSomething() {
		System.out.println("--------------------");
		System.out.println("I'm doing something.");
		System.out.println("--------------------");

	}

	public void sendEsception() throws Exception {
		throw new Exception("Exception");
	}

	@Override
	public String toString() {
		return "ServiceImpl []";
	}

}
package net.prietopalacios.josemanuel.aop;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

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

@Aspect
public class AopService {

	private Map<Integer, Integer> sessions;
	private Map<Integer, Integer> history;

	public AopService() {
		this.sessions = new HashMap<Integer, Integer>();
		this.history = new HashMap<Integer, Integer>();
	}
	
	@Before(value="(execution(* net.prietopalacios.josemanuel.aop.service.*.*(..)))")
	public void startsession(JoinPoint joinPoint) throws Exception {  
		int hashCode = joinPoint.hashCode();
		int session = startSession();
		startSession(hashCode, session);

		System.out.println("==================");
		System.out.println("BEFORE: ");
		System.out.println("hashCode: " + hashCode);
		System.out.println("session: " + session);
	}

	@AfterThrowing(value="(execution(* net.prietopalacios.josemanuel.aop.service.*.*(..)))", throwing="exception")
	public void afterThrowingStopSession(JoinPoint joinPoint, Exception exception) throws Exception {  
		int hashCode = joinPoint.hashCode();
		int session = sessions.get(hashCode);

		System.out.println("AFTERTHROWING: ");
		System.out.println("hashCode: " + hashCode);
		System.out.println("session: " + session);

		stopSession(hashCode, session);
	}

	@After(value="(execution(* net.prietopalacios.josemanuel.aop.service.*.*(..)))")  
	public void afterStopSession(JoinPoint joinPoint) throws Exception {  
		int hashCode = joinPoint.hashCode();
		if(!sessions.containsKey(hashCode)) return;
		int session = sessions.get(hashCode);

		System.out.println("AFTER: ");
		System.out.println("hashCode: " + hashCode);
		System.out.println("session: " + session);

		stopSession(hashCode, session);
	}

	private int startSession(){
		Random randomGenerator = new Random();
		return randomGenerator.nextInt(100);
	}

	private void startSession(int hashCode, int session) throws Exception{
		if(sessions.containsKey(hashCode)) {
			throw new Exception ("Ya existe la clave: " + hashCode);
		}
		sessions.put(hashCode, session);
		history.put(hashCode, session);
	}

	private void stopSession(int hashCode, int session) throws Exception{
		printMap();
		int remove = sessions.remove(hashCode);
		if(remove != session) throw new Exception("Imposible cerrar conexion");
	}
	
	private void printMap(){
		int n=1;
		for(Entry<Integer, Integer> entry: history.entrySet()){
			System.out.println(n++ + ".- (h)clave: " + entry.getKey() + ", valor:" + entry.getValue());
		}
		n=0;
		for(Entry<Integer, Integer> entry: sessions.entrySet()){
			System.out.println(n++ + ".- (s)clave: " + entry.getKey() + ", valor:" + entry.getValue());
		}
	}
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<aop:aspectj-autoproxy />

	<bean id="service" class="net.prietopalacios.josemanuel.aop.service.ServiceImpl" />
	<bean id="aop" class="net.prietopalacios.josemanuel.aop.AopService" />

</beans>  
package net.prietopalacios.josemanuel.aop.service;

import static org.junit.Assert.assertTrue;

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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.xml")
public class ServiceImplTest {
	
	@Autowired
	Service service;

	@Test
	public void testDoSomething() {
		try {
			service.sendSomething();
			service.sendSomething();
			assertTrue(true);
		} catch (Exception e) {
			if(e.getMessage() != null){
				assertTrue(e.getMessage(), false);	
			}else{
				assertTrue(e.getCause().getMessage(), false);
			}
		}
		
	}
	
	@Test
	public void testThrowEsception() {
		try {
			service.sendEsception();
			assertTrue(true);
		} catch (Exception e) {
			if(e.getMessage() != null){
				assertTrue(e.getMessage(), false);	
			}else{
				assertTrue(e.getCause().getMessage(), false);
			}
		}
	}

}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>net.prietopalacios.josemanuel</groupId>
	<artifactId>aop</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>aop_example</name>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjtools</artifactId>
			<version>1.7.3</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>3.0.5.RELEASE</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

</project>
Anuncios
Spring AOP start close connection con anotaciones

Componente vs Aspecto

<!– @page { margin: 2cm } P { margin-bottom: 0.21cm } –>

Un componente es aquella propiedad que se puede encapsular fácilmente en un procedimiento, mientras que, un aspecto no se puede encapsular en un procedimiento con los lenguajes tradicionales. Ejemplo de aspecto es el login o acceso. Necesitas saber si una persona esta logada o no, durante toda la aplicación.

Componente vs Aspecto