---
title: "Google guice 入门教程04--简单AOP应用"
author: "carvin"
date: "2010-12-21T10:42:06Z"
tags: ["AOP", "Google", "Java", "编程", "设计模式"]
categories: ["编程语言"]
slug: "google-guice-04-aop"
draft: false
lastmod: "2010-12-21T10:43:27Z"
id: 847860
url: "https://carvin.iteye.com/blog/847860"
---

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

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

```


2、实现接口AOPServiceImpl.java

```java

public class AOPServiceImpl implements IAOPService {

	@Override
	@Log
	public void execute(String name) {
		System.out.println(name + " execute this method.");
	}

}

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

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

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

```java

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

```java

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、实现测试类

```java

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应用就完成了。