简体   繁体   English

在Spring中将变量传递给@Qualifier批注

[英]Passing variables to @Qualifier annotation in Spring

Is it possible to pass a variable to the @Qualifier annotation in Spring? 是否可以在Spring中将变量传递给@Qualifier批注?

For example, 例如,

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

I have 10 different databases where my Spring batch job runs everyday. 我有10个不同的数据库,我的Spring批处理每天都在其中运行。 The database number is passed as a job parameter. 数据库号作为作业参数传递。 I want to define the datasource to connect to based on the job parameter. 我想基于job参数定义要连接的数据源。

Thanks! 谢谢!

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?? 因此,您要在Spring配置中创建10个数据源-您的工作是否需要一次运行使用全部十个数据源? If you only need one connection for the lifetime of your spring context, can you just have 10 different sets of property files? 如果您在Spring上下文的整个生命周期中只需要一个连接,那么您是否可以拥有10组不同的属性文件?

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... 您可以做的一件事是在地图中创建所有数据源(以“数据库号”作为键,然后将此地图和密钥注入到您的bean中,例如...

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? 还是我误会了?

no, you can't pass variables to any annotations in java. 不,您不能将变量传递给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 创建并传递一项服务,该服务将在每次需要时选择正确的数据库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM