Aop 简单实例

一 , 定义aop

@Aspect
@Component
public class MyAspect {
    //* com 这里有个 空格 !
    @Pointcut("execution(* com.example.demo.Service.HelloServiceImpl.sayHello(..))")
    public void pointCut(){}
 
    @Before("pointCut()")
    public void before()
    {
        System.out.println("befor....");
    }
 
    @AfterReturning("pointCut()")
    public void afterReturning()
    {
        System.out.println("afterReturning....");
    }
 
    @After("pointCut()")
    public void after()
    {
        System.out.println("after....");
    }
 
    @AfterThrowing("pointCut()")
    public void afterThrowing()
    {
        System.out.println("afterThrowing....");
    }
}

二 , 定义 service 和 impl

service:

public interface IHelloService {
    void sayHello(String name);
}

impl:

@Service("hello")
public class HelloServiceImpl implements IHelloService {
 
    @Override
    public void sayHello(String name) {
        System.out.println(name +" : hello");
    }
}

三 , 测试

@Test
    public void contextLoads() {
        helloService.sayHello("tyler");
    }

四 , 结果

原文地址:https://www.cnblogs.com/hanjun0612/p/11113160.html