ITeye博客

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

carvin · 2010-12-21 10:42 · google framework · 编程语言 · Java · Google · AOP · 编程 · 设计模式 · Markdown

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)

暂无评论。

评论功能维护中,当前仅展示历史评论。