Thursday, April 2, 2009

Autowire datasource by name for Spring test base class

Suppose you extends AbstractTransactionalJUnit4SpringContextTests but you have multiple datasource beans. When the context is loaded, Spring will complain that it could not setDatasource() for AbstractTransactionalJUnit4SpringContext because there is more than one bean with the type.

The solution is described here in Spring Docs.

If you are extending from a Spring-provided test base class that happens to use @Autowired on one of its setters methods, you might have multiple beans of the affected type defined in your application context: e.g. multiple DataSource beans. In such a case, you may override the setter and use the @Qualifier annotation to indicate a specific target bean as follows:

...
@Override @Autowired
public void setDataSource(@Qualifier("myDataSource") DataSource dataSource) {
super.setDataSource(dataSource);
}
...

No comments:

Post a Comment