我已经开始从事Spring Boot一段时间了。对于一个项目,我正在尝试使用工厂bean来创建数据源。最终,我需要从另一个数据库表动态创建数据源。我有一个原型bean,每次调用context.getBean(“ getDbEndpointDatasource”,args ....)都会创建一个新的数据源
@Bean
@Scope("prototype")
@Qualifier("getDbEndpointDatasource")
public DataSource getDbEndpointDatasource(String url, String className, String userName, String password) {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(url);
dataSource.setDriverClassName(className);
dataSource.setUsername(userName);
dataSource.setPassword(password);
return dataSource;
}
我正在通过以下方式获取数据源。
DataSource getDbEndpointDatasource = (DataSource) context.getBean("getDbEndpointDatasource",
"jdbc:postgresql://127.0.0.1/spring-test?user=spring-test&password=spring",
"org.postgresql.Driver", "spring", "spring");
因此,使用上述配置,启动spring boot时出现以下异常。
Caused by: java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 103 more
我已经搜索了一段时间,为什么spring给出了这个例外。我还有另一个工厂Bean,该工厂Bean也具有原型范围,每次按预期调用它时,都会给我一个新对象。但是在这里,我不明白为什么会出现此错误。我传递给context.getBean方法的参数数量似乎正确。另外,如果删除Scope注释,我也不会例外,但是每次调用都会给我相同的数据源。我不确定我是否想念任何东西。对我来说似乎很奇怪。
我很高兴有人可以提供提示或指导。
谢谢
答案 0 :(得分:1)
您能尝试以下吗?
DataSource endpointDatasource = (DataSource) context.getBean("getDbEndpointDatasource");
endpointDatasource.getDbEndpointDatasource("jdbc:postgresql://127.0.0.1/spring-test?user=spring-test&password=spring","org.postgresql.Driver", "spring", "spring");