1.编写UserService的接口(目标类)
package com.zslaa.service;
public interface UserService {
public void save(String name);
public void update();
}
2.编写UserServiceImpl的实现
package com.zslaa.service.impl;
import org.springframework.stereotype.Service;
import com.zslaa.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Override
public void save(String name) {
System.out.println("执行save方法,name为:"+name);
}
@Override
public void update() {
System.out.println("执行update方法");
}
}
3.编写纯注解的切面类
package com.zslaa.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
@Before(value = "execution(public * com.zslaa.service.impl.UserServiceImpl.*(..))")
public void before() {
System.out.println("前置通知");
}
@After(value = "execution(public * com.zslaa.service.impl.UserServiceImpl.*(..))")
public void after() {
System.out.println("最终通知");
}
@AfterReturning(value = "execution(public * com.zslaa.service.impl.UserServiceImpl.*(..))")
public void afterReturning() {
System.out.println("后置通知");
}
@AfterThrowing(value = "execution(public * com.zslaa.service.impl.UserServiceImpl.*(..))")
public void afterThrowing() {
System.out.println("异常通知");
}
@Around(value = "execution(public * com.zslaa.service.impl.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint pjp) {
System.out.println("前置通知--前面代码");
try {
pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("前置通知--后面代码");
}
}
4.编写Spring配置类
package com.zslaa.test;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configurable
@ComponentScan(basePackages="com.yiidian")
@EnableAspectJAutoProxy
public class SpringConfig {
}
5编写测试类
package com.zslaa.test;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.zslaa.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SpringConfig.class)
public class Demo1 {
@Resource
private UserService userService;
@Test
public void test1(){
customerService.update();
}
}
6.运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9aaae7bf414620a9b86ae78ada69e27e.png)