I am newbie in Spring. I use AbstractRoutingDataSource to change db connection in runtime and SpringBoot My code is similar to this https://spring.io/blog/2007/01/23/dynamic-datasource-routing but beans are configured programatically.
public class DatabaseContext {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setDatabaseType(String string) {
contextHolder.set(string);
}
public static String getDatabaseType() {
return (String) contextHolder.get();
}
public static void clearDatabaseType() {
contextHolder.remove();
}
}
Everything works fine when I change context like that (pseudocode):
public class Application {
@Autowired
private MyCrudRepository repository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override run(){
DatabaseContext.changeContext("db1");
repository.findAll(); //data from db1 like expected
DatabaseContext.changeContext("db2");
repository.findAll(); //data from db2 like expected
}
}
but when I change context in servlet class (pseudocode)
@Controller
public class MyWebController{
@RequestMapping(someMapping)
HttpEntity someMethod(){
DatabaseContext.changeContext("db1");
repository.findAll(); //data from db1 like expected
DatabaseContext.changeContext("db2");
repository.findAll(); //data from db1
}
}
Context change just one time and I have no idea what's wrong.