SpringBoot多数据源之AOP(四)
- 1.自定义注解
- 2.切面类
- 3.使用注解
1.自定义注解
这里定义了一个注解WR
,作用在方法和类上,同时注解中value
的默认值为W
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface WR {String value() default "W";
}
2.切面类
导入相关的AOP
依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>
定义一个切面类DynamicDataSourceAspect.java
@Component
@Aspect
public class DynamicDataSourceAspect {@Before("within(com.rql.controller.*) && @annotation(wr)")public void before(JoinPoint joinPoint, WR wr) {String name=wr.value();DynamicDataSource.name.set(name);System.out.println(name);}
}
3.使用注解
这里在方法上添加了注解:
@RestController
@RequestMapping("user")
public class UserController {@Autowiredprivate UserDao userDao;@GetMapping("/a")@WR("R")public List<User> selectUsers(){return userDao.findAll();}@PostMapping("/b")@WR("W")public void insertUser(@RequestBody User user){userDao.inserUser(user);}}