Friday, June 20, 2014

Aop with Juice

package aop1;

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

public class AopInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("Interceptor: before");
Object o = invocation.proceed();
System.out.println("Interceptor: Done !");
return o;
}
}


package aop1;

import com.google.inject.AbstractModule;
import com.google.inject.matcher.Matchers;

public class AopModule extends AbstractModule {

 @Override
 protected void configure() {
 bind(BasicDummyService.class);
 bind(Service1.class);
 bind(Service2.class);
 bind(Service3.class);
 bindInterceptor(Matchers.any(),Matchers.annotatedWith(InjectedTransaction.class),new AopInterceptor());
 }
}

package aop1;

public class BasicDummyService {

 @InjectedTransaction
 public void testService() {
 System.out.println("doing testService");
 }
 @InjectedTransaction
 public void testService1() throws Exception{
throw new Exception();
// System.out.println("doing testService");
 }
}

package aop1;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
public @interface InjectedTransaction {

}

package aop1;

import org.junit.Test;

import com.google.inject.Guice;
import com.google.inject.Injector;

public class Main {
@Test
void Mehtod(){
Injector injector = Guice.createInjector(new AopModule());
BasicDummyService test = injector.getInstance(BasicDummyService.class);
Service1 test1 = injector.getInstance(Service1Impl.class);
Service2 test2 = injector.getInstance(Service2Impl.class);
Service3 test3 = injector.getInstance(Service3Impl.class);

try {
test.testService();
} catch (Exception e) {


}
test1.Method1(new Object());
try {
test2.Method1(new Object());
} catch (Exception e) {
e.printStackTrace();
}
test3.Method1(new Object());
}
}

package aop1;

public interface Service1 {
Object Method1(Object test);

}


package aop1;

public class Service1Impl  implements Service1 {
@InjectedTransaction
@Override
public Object Method1(Object test) {
System.out.println("I am service1");
return test;
}

}


package aop1;

public interface Service2 {
Object Method1(Object test) throws Exception;

}

package aop1;

public class Service2Impl implements Service2{
@InjectedTransaction
@Override
public Object Method1(Object test) throws Exception {
System.out.println("I am service2");
return test;
}

}

package aop1;

public interface Service3 {
Object Method1(Object test) throws RuntimeException;
}

package aop1;

public class Service3Impl implements Service3 {
@InjectedTransaction
@Override
public Object Method1(Object test) throws RuntimeException {
System.out.println("I am service3");
return null;
}

}

No comments:

Post a Comment