aop增强类后无法通过getBean()来获取bean对象

被aop增强的类:
接口

public interface IUserService {
    void findUserById(int id);
}

实现类:

@Service
@Setter
public class UserServiceImpl implements IUserService{
    @Override
    public void findUserById(int id) {
        System.out.println("找到一个用户");
    }

}

aop切面

@Component
@Aspect
public class AopAdvice {
    @Before("execution(* com.idea.spring.service.Impl.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("---------方法执行前before()---------");
    }
}

通过getBean()进行调用时出现报错如下:
No qualifying bean of type ‘com.idea.spring.service.Impl.UserServiceImpl’ available

经过百度什么的查看发现应该是aop切面插入后该bean被jdk内部自动转为了com.sun.proxy.$Proxy25类型类型已被转变,所以无法通过类UserServiceImpl进行获取
经测试发现可以通过接口IUserService或byName获取
获取后如何执行该类的方法呢?

经过一段思考后发现可以用反射来实现

@Test
    public void testService() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");

        Object userService = applicationContext.getBean(IUserService.class);

        Method method = userService.getClass().getMethod("findUserById", int.class);

        method.invoke(userService,1);

    }

该问题终于得到了解决。。。。。。。。。。。。。。。。。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值