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!

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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!
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.