---
title: "Aspectj 入门(一)"
author: "fys124974704"
date: "2008-12-30T21:14:18Z"
tags: ["AOP", "Eclipse", "Spring"]
slug: "aspectj"
draft: false
lastmod: "2008-12-30T21:26:32Z"
id: 307252
url: "https://vincent-yy.iteye.com/blog/307252"
---

由于Spring的配置过多，个人不喜欢！但是又想使用一下AOP，所以选择了Aspectj ，用起来比Spring自然一点，至少不用我去写那些可恶的配置文件！

      讲讲Aspectj怎么用，首先去eclipse官方下载一个Aspectj的插件，挺好用的！安装到eclipse里面，安装步骤省略！

      入门先讲讲前拦截和后拦截

      先写两个Java文件

 

    

```
public class Test {
	public static void main(String[] args) {
		HelloWorld.deliver("Wanna learn AspectJ?");
		HelloWorld.deliver("Harry", "having fun?");
		HelloWorld.round("round");
	}
}
```

 

 

```
public class HelloWorld {
	public static void deliver(String message) {
		System.out.println(message);
	}

	public static void deliver(String person, String message) {
		System.out.print(person + ", " + message);
	}

 	public static void round(String s){
 	 	 System.out.println(s);
 	}
}
```

 

 

 

这两个文件可以运行，肯定没有问题！因为....太简单了！

 

再写一个拦截上面两个方法的类

```
aspect MannersAspect {
	// 定义切点 并且指明在哪个方法
	pointcut deliverMessage() : call(* HelloWorld.deliver(..));

	pointcut afterMessage() : call (* HelloWorld.deliver(..));
	
	pointcut roundMessage(String s) : call (* HelloWorld.round(String)) && args(s);
	// 方法前拦截
	before() : deliverMessage() {
		System.out.println("before! ");
	}

	// 方法后拦截
	after() : afterMessage(){
		System.out.println("after! ");
	}

	 void around(String s) : roundMessage(s) {
  		proceed("99 "+s+" 00 ");
 	}
	
}
```

  

 

为什么建议使用eclipse插件呢，因为没有插件这个类会报错的！不能编译怎么运行呢？是不是！

 

 

 

简单的入门  完