---
title: "Spring AOP"
author: "txazo"
date: "2012-09-05T12:32:46Z"
tags: []
categories: ["编程语言"]
slug: "spring-aop"
draft: false
lastmod: "2012-09-05T12:32:46Z"
id: 1671799
url: "https://txazo.iteye.com/blog/1671799"
---

1. Spring AOP
2. Spring AOP注解

1. Spring AOP
1)切面类

```java

public class LogAspect {

	public void before() {
		System.out.println("Before");
	}

	public Object around(ProceedingJoinPoint proceedingJoinPoint)
			throws Throwable {
        System.out.println("Around Begin");  
		long time = System.currentTimeMillis();
		Object object = proceedingJoinPoint.proceed();
		time = System.currentTimeMillis() - time;
		System.out.println("Around After: " + time + "ms");
		return object;
	}

	public void after() {
		System.out.println("After");
	}

}

```

2)applicationContext.xml

```xml

<bean id="logAspect" class="com.txazo.aop.LogAspect" />

<aop:config>
	<aop:aspect id="logAspect" ref="logAspect">
		<aop:pointcut id="service" expression="
            execution(* com.txazo.service.impl.*Impl.*(..))" />
		<aop:before pointcut-ref="service" method="before" />
		<aop:around pointcut-ref="service" method="around" />
		<aop:after pointcut-ref="service" method="after" />
	</aop:aspect>
</aop:config>

```

2. Spring AOP注解
1)切面类

```java

@Aspect
@Component
public class LogAspect {

	@Pointcut("execution(* com.txazo.service.impl.*Impl.*(..))")
	private void pointcut() {

	}

	@Before("pointcut()")
	public void before() {
		System.out.println("Before");
	}

	@Around("pointcut()")
	public Object around(ProceedingJoinPoint proceedingJoinPoint)
			throws Throwable {
        System.out.println("Around Begin");  
		long time = System.currentTimeMillis();
		Object object = proceedingJoinPoint.proceed();
		time = System.currentTimeMillis() - time;
		System.out.println("Around After: " + time + "ms");
		return object;
	}

	@After("pointcut()")
	public void after() {
		System.out.println("After");
	}

}

```

2)applicationContext.xml

```xml

<aop:aspectj-autoproxy />

<context:component-scan base-package="com.txazo" />

```