Java service类中调用同类中的另一个方法时,aop不生效的解决方法

1:演示代码内容
1.1:Controller
package com.ydg.cloud.lock.controller;

import com.ydg.cloud.lock.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author YDG
 * @description
 * @since 2019-04-23
 */
@Slf4j
@RestController
public class TestLockController {


    @Autowired
    private TestService testService;

    @GetMapping("test")
    public void test() {
        testService.testLock(1L);
    }
}

1.2:Service
package com.ydg.cloud.lock.service;

/**
 * @author YDG
 * @description
 * @since 2019-07-20
 */
public interface TestService {

    void testLock(Long id);

    void testLock2(Long id);
}
1.3:ServiceImpl
package com.ydg.cloud.lock.service.impl;

import com.ydg.cloud.lock.annotation.Lock;
import com.ydg.cloud.lock.service.TestService;
import org.springframework.stereotype.Service;

/**
 * @author YDG
 * @description
 * @since 2019-07-20
 */
@Service
public class TestServiceImpl implements TestService {

    @Override
    public void testLock(Long id) {
        assert id != null;
        this.testLock2(id);
    }

    @Override
    @Lock(keyName = "id")
    public void testLock2(Long id) {
        System.out.println("需要加锁的id是:" + id);
    }
}

2:不生效

如上面的代码,在controller中注入了TestSevice,然后调用了TestService的testLock方法,在testLock方法中调用了testLock2方法,其中testLock2方法上面加了@Lock注解,这个注解是我自己写的一个分布式锁注解,里面用到了aop,会在进入加了@Lock注解的方法的时候,将keyName作为分布式锁的key对资源进行加锁,但是实际的执行状况是aop不生效

3:使之生效
package com.ydg.cloud.lock.service.impl;

import com.ydg.cloud.lock.annotation.Lock;
import com.ydg.cloud.lock.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

/**
 * @author YDG
 * @description
 * @since 2019-07-20
 */
@Service
public class TestServiceImpl implements TestService {
    @Autowired
    private ApplicationContext applicationContext;

    @Override
    public void testLock(Long id) {
        assert id != null;
        TestService testService = applicationContext.getBean(TestService.class);
        testService.testLock2(id);
    }

    @Override
    @Lock(keyName = "id")
    public void testLock2(Long id) {
        System.out.println("需要加锁的id是:" + id);
    }
}

我换了种方法,通过applicationContext拿到TestService的cglib动态代理对象,就行了,就能在testLock方法调用testLock2方法的时候使testLock2的aop生效

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值