You can create a configuration in your project, which builds a new data source annotated as @Primary
bean. This new data source will be the datasource1
, which will be injected by spring to the new data source factory method. Here you have the working example.
The config:
@SpringBootApplication
public class BeanSpringExampleApplication
{
@Bean(name = "dataSource1")
public FakeDataSource dataSource1()
{
return new FakeDataSource("dataSource1");
}
@Bean(name = "dataSource2")
public FakeDataSource dataSource2()
{
return new FakeDataSource("dataSource2");
}
@Bean
@Primary
public FakeDataSource primaryDataSource(
@Qualifier("dataSource1") FakeDataSource dataSource1)
{
return dataSource1;
}
}
Here you see three beans (using FakeDataSource
class), which simulate your situation. The primaryDataSource
bean factory method simply returns the dataSource1
(it's just a mere data source selector).
The FakeDataSource
is just a placeholder, to make example runnable:
public class FakeDataSource
{
private final String fakeProperty;
public FakeDataSource(String id)
{
fakeProperty = id;
}
/**
* @return the fakeProperty
*/
public String getFakeProperty()
{
return fakeProperty;
}
}
Finally, a test which proves everything is working:
@RunWith(SpringRunner.class)
@SpringBootTest
public class BeanSpringExampleApplicationTests
{
@Autowired
private FakeDataSource fakeDataSource;
@Test
public void should_AutowirePrimaryDataSource() throws Exception
{
assertEquals("dataSource1", fakeDataSource.getFakeProperty());
}
}