SpringAop的简单代码实现

这是一篇使用aop思想实现对业务层功能的增强(加日志)的文章,网上关于aop的基础知识以及如何理解都非常多,这里不一一赘述。文章目的是作为本人学习记录、以及还暂时没有搞懂aop的各位,也许 就突然懂了

看完本片文章需要理解的几件事情
1、对aop的理解
2、aop的基本概念以及各个通知方法的区别
3、文中各个地方的具体写法,为什么
4、通知方法的执行顺序

aop的具体使用详解

@Service
public class HelloService {

    public void hello1() {
        System.out.println("我是类的业务方法1");
    }

    public void hello2() {
        System.out.println("我是类的业务方法2");
    }

    public void hello3() {
        System.out.println("我是类的业务方法3");
    }
}

@Aspect
@Component
public class HelloAspect {
    @Pointcut(value = "execution(* com.newtouc.energy.business.aop.HelloService.*(..))")
    public void pointCut() {
        // Do nothing
    }

    @Before("pointCut()")
    public void beforeService() {
        System.out.println("日志开始了");
    }

    @After("pointCut()")
    public void afterService() {
        System.out.println("日志结束了");
    }

    @Around("pointCut()")
    public void aroundService(ProceedingJoinPoint pjp) {
        System.out.println("日志开始时间----------" + new Date());
        try {
            pjp.proceed(); //执行业务方法
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("日志结束时间----------" + new Date());
    }
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTests {

    @Autowired
    private HelloService helloService;

    @Test
    public void contextLoads() {
        //设置用户名
//        CurrentUserHolder.set("hello");

        helloService.hello1();
        helloService.hello2();
        helloService.hello3();
    }
}

执行结果(如图):
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值