The last article was tested under the main method. In this article, I will serve you bloggers in the end. It is encapsulated into a tool class and can be called directly! Not much to say about the code:
public class DataSourceSwitch {
@DataSource(value = "slave1")
public static void change(String data)throws Exception{
Method method = DataSourceSwitch.class.getMethod("change", String.class);
DataSource dataSource = method.getAnnotation(DataSource.class);
if (dataSource ==null){
throw new RuntimeException("请添加数据源");
}
InvocationHandler invocationHandler = Proxy.getInvocationHandler(dataSource);
Field value = invocationHandler.getClass().getDeclaredField("memberValues");
value.setAccessible(true);
Map<String,Object> memberValues = (Map<String, Object>) value.get(invocationHandler);
String val = (String) memberValues.get("value");
System.out.println("改变前"+val);
val = data;
memberValues.put("value",val);
System.out.println("改变后"+dataSource);
}
}
The blogger reported the error here several times mainly for the following reasons: 1: your value was wrongly transmitted, 2: there are more spaces, and you can grasp it yourself
Use of methods
DataSourceSwitch.change("druid");
Inside is the value of the value that I want to switch, I tested it can be switched