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生效