I have defined a bean in dispatcher-servlet.xml
like this:
<!-- Datasource configuration -->
<beans:bean id="dataSource" name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="" />
<beans:property name="username" value="" />
<beans:property name="password" value="" />
</beans:bean>
In another config.class
(this time using Java Annotation for configuration) I would want to override this bean. This is the definition of the new bean:
@ImportResource(dispatcher-servlet.xml)
@Bean
@Primary
public EmbeddedDatabase dataSource() {
EmbeddedDatabaseBuilder databaseBuilder = new EmbeddedDatabaseBuilder();
databaseBuilder.setName("testDB");
databaseBuilder.setType(EmbeddedDatabaseType.H2);
return databaseBuilder.build();
}
In a test I write:
@ContextConfiguration(classes = config.class)
@WebAppConfiguration
// Test
The unexpected result is that the bean with id dataSource that Spring chooses is the one defined in the xml file. This is the output logged:
[info] Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=true; factoryBeanName=Config; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in ... with [Generic bean: class [org.springframework.jdbc.datasource.DriverManagerDataSource]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in URL [dispatcher-servlet.xml]]
It seems that @Primary
Annotation is ignored.
Why? What is the solution?