Google guice 入门教程04--简单AOP应用

AOP简介
 面向切面编程(也叫面向方面):Aspect Oriented Programming   AOP是OOP的延续,是(Aspect Oriented Programming)的缩写,意思是面向切面(方面)编程。   主要的功能是:日志记录,性能统计,安全控制,事务处理,异常处理等等。   
主要的意图是:将日志记录,性能统计,安全控制,事务处理,异常处理等代码从业务逻辑代码中划分出来,通过对这些行为的分离,我们希望可以将它们独立到非指导业务逻辑的方法中,进而改变这些行为的时候不影响业务逻辑的代码。   可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。AOP实际是GoF设计模式的延续,设计模式孜孜不倦追求的是调用者和被调用者之间的解耦,AOP可以说也是这种目标的一种实现。

Guice AOP应用(这里以日志为例)
1、定义一个服务接口IAOPService.java

public interface IAOPService {
void execute(String name);
}


2、实现接口AOPServiceImpl.java

public class AOPServiceImpl implements IAOPService {

@Override
@Log
public void execute(String name) {
System.out.println(name + " execute this method.");
}

}


3、定义一个Log的注解,作用是在需要日志的方法上加上此注解

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

}

4、实现Log 方法拦截类,这里要实现Guice提供的AOP接口MethodInterceptor

public class LogInterceptor implements MethodInterceptor {

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("[" + invocation.getMethod().getName() + " ]method begin.");
long beginTime = System.currentTimeMillis();
System.out.println("begin time : " + beginTime);
Object ret = invocation.proceed();
System.out.println("[" + invocation.getMethod().getName() + " ]method end.");
long endTime = System.currentTimeMillis();
System.out.println("end time : " + endTime);
System.out.println("method invoked time : " + (endTime - beginTime));
return ret;
}
}

在这里实现的是在方法执行前后输出一些信息。

5、实现Module

public class LogModule extends AbstractModule {

@Override
protected void configure() {
bindInterceptor(Matchers.any(), Matchers.annotatedWith(Log.class), new LogInterceptor());
bind(IAOPService.class).to(AOPServiceImpl.class);
}
}


6、实现测试类

public class LogTest {
@Inject
private IAOPService aopService;
public static void main(String[] args) {
LogTest logTest = Guice.createInjector(new LogModule()).getInstance(LogTest.class);
logTest.aopService.execute("carvin");
}
}


到此,一个简单的Log AOP应用就完成了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值