Skip to content

Commit dfb86af

Browse files
committed
修复动态切换数据源类注解不生效
1 parent 04d2eb8 commit dfb86af

File tree

4 files changed

+8
-3
lines changed

4 files changed

+8
-3
lines changed

chapter5/src/main/java/com/yukong/chapter5/aop/DynamicDataSourceAnnotationAdvisor.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,11 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
4545

4646
private Pointcut buildPointcut() {
4747
Pointcut cpc = (Pointcut) new AnnotationMatchingPointcut(DataSource.class, true);
48+
// 类注解
49+
Pointcut clpc = (Pointcut) AnnotationMatchingPointcut.forClassAnnotation(DataSource.class);
50+
// 方法注解
4851
Pointcut mpc = (Pointcut) AnnotationMatchingPointcut.forMethodAnnotation(DataSource.class);
49-
return new ComposablePointcut(cpc).union(mpc);
52+
return new ComposablePointcut(cpc).union(clpc).union(mpc);
5053
}
5154

5255
}

chapter5/src/main/java/com/yukong/chapter5/register/DynamicDataSourceRegister.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,8 @@ private Class<? extends DataSource> getDataSourceType(String typeStr) {
132132
}
133133
return type;
134134
} catch (Exception e) {
135-
throw new IllegalArgumentException("can not resolve class with type: " + typeStr); //无法通过反射获取class对象的情况则抛出异常,该情况一般是写错了,所以此次抛出一个runtimeexception
135+
//无法通过反射获取class对象的情况则抛出异常,该情况一般是写错了,所以此次抛出一个runtimeexception
136+
throw new IllegalArgumentException("can not resolve class with type: " + typeStr);
136137
}
137138
}
138139

chapter5/src/main/java/com/yukong/chapter5/repository/UserMapper.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
* @Date: 2018/8/13 19:47
1212
* @Description: UserMapper接口
1313
*/
14+
@DataSource("slave1")
1415
public interface UserMapper {
1516

1617
/**
@@ -49,6 +50,5 @@ public interface UserMapper {
4950
* 查询所有用户信息
5051
* @return
5152
*/
52-
@DataSource("slave2") //slave2
5353
List<User> selectAll();
5454
}

chapter5/src/main/java/com/yukong/chapter5/service/UserService.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ public class UserService {
1616

1717
@Autowired
1818
private UserMapper userMapper;
19+
1920
public void testTransactional() {
2021
User user = new User();
2122
user.setUsername("Transactional");

0 commit comments

Comments
 (0)