AOP开发中的一个坑:使用AOP添加的额外方法在业务方法间调用中没有执行

本文介绍了在Spring AOP开发中遇到的一个问题,即同一个业务类内方法间的调用导致额外功能(切面)未生效。通过实现ApplicationContextAware接口并保存ApplicationContext,然后在方法调用时通过上下文获取代理对象来执行方法,成功解决了这个问题。这种方法避免了直接创建ApplicationContext对象,确保了资源的有效利用。
摘要由CSDN通过智能技术生成

AOP开发中的一个坑

1. 问题描述

在同一个业务类中,业务方法间进行调用,如方法a调用了方法b,两个方法都增加了额外功能,但是最后在实际调用过程中只有a方法的额外功能实现了,b没有实现。

public void a() {
	b();
}

public void b() {
	...
}

2. 解决方案

实现ApplicationContextAware接口重写setApplicationContext()方法,将ApplicationContext作为成员变量在setApplicationContext()方法中进行赋值,在调用中使用ApplicationContext对象获取代理对象执行方法。

注意: 不要在方法中创建ApplicationContext对象,因为这个对象代表了Spring工厂,占用资源多,一个程序中应该只存在一个。

代码:

import com.jc.aspect.UserService;
import com.jc.bean.User;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class UserServiceImpl implements UserService, ApplicationContextAware {
    private ApplicationContext ctx;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }

    @Override
    public boolean login(String username, String password) {
        System.out.println("UserServiceImpl.login");
//        register(new User());
        UserService userService = (UserService) ctx.getBean("UserService");
        userService.register(new User());
        return true;
    }

    @Override
    public void register(User user) {
        System.out.println("UserServiceImpl.register");
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神烦狗闯入了你的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值