2

Is it possible to pass a variable to the @Qualifier annotation in Spring?

For example,

@Autowried
@Qualifier("datasource_" + "#{jobParameters['datasource.number']}")
private DataSource ds;

I have 10 different databases where my Spring batch job runs everyday. The database number is passed as a job parameter. I want to define the datasource to connect to based on the job parameter.

Thanks!

GC_25
  • 60
  • 1
  • 7

2 Answers2

3

You are only allowed constant expressions in annotations.

So you are creating 10 data sources in your spring configuration - does your job need to use all ten in one run?? If you only need one connection for the lifetime of your spring context, can you just have 10 different sets of property files?

One thing you could do is to create all of your data sources in a map (keyed by "database number", then inject this map AND the key into your bean, for example...

public class MyBean {
    @Autowired @Qualifier("dataSourceMap")
    private Map<String, DataSource> dataSourceMap;

    @Value("#{jobParameters['datasource.number']}")
    private String dbKey;

    public void useTheDataSource() {
        DataSource ds = dataSourceMap.get(dbKey);

        ...
    }
}

Or have I misunderstood?

BretC
  • 4,141
  • 13
  • 22
  • Thanks Bret! All the jobs need to run in parallel, and the jobs are triggered via the @Scheduled annotation which creates the 10 jobs and runs it (I am using SpringBoot). Based on my app structure, I have done something very similar to what you have suggested. Thanks for the help! – GC_25 Feb 18 '15 at 18:35
2

no, you can't pass variables to any annotations in java. it has nothing to do with spring.

use a workaround. create and pass a service that will pick correct database each time it's needed

piotrek
  • 13,982
  • 13
  • 79
  • 165