是否可以将@Qualifier注释设置为Java类中的私有静态变量



我目前正在使用JDBC模板从数据库中获取数据。为此,我创建了一个"静态"Repository类(即一个标记为"final"并带有单个私有构造函数的类)。在它中,我试图设置两个私有静态PlatformTransactionManager类变量的值。

然而,我的IntelliJ告诉我类变量的值总是空的,我不知道如何解决这个问题。

我希望在静态构造函数中将它们用作局部变量,因为我真正想要的是使用PTM准备的JdbcTemplate常量。由于我不知道如何做到这一点,我尝试将它们制作成private static final字段。但IntelliJ也不允许这样做。

为了解决这个问题,我研究了以下线程:

  • 在Spring中将变量传递给@Qualifier注释
  • 如何使spring在静态字段中注入值

。以及关于限定符的注释:

  • Java EE 6教程:使用限定符

重要说明:

  • 我正在处理的项目没有XML配置文件。项目中有[*]个配置文件用于处理配置
  • 还有一点需要注意的是,我一般不太理解注释(无论是Java、C#等)。也就是说,我知道它们背后的基本思想,但我不知道它们是如何真正工作的。我对Spring框架的记忆已经不多了(因为我已经在Core Java和C#.NET上工作了很长一段时间)。所以如果能帮我解决这个问题,我将不胜感激

以下是我的源代码的示例:

private final class Repository {
private Repository() {}
private static final JdbcTemplate TEMPLATE1;
private static final JdbcTemplate TEMPLATE2;
@Qualifier( "transactionManager1" )
private static PlatformTransactionManager manager1;
@Qualifier( "transactionManager2" )
private static PlatformTransactionManager manager2;
static {
// NOTE: For this one, IntelliJ shows me an error stating, "Value 'manager1'
// is always 'null'."
DataSource source =
( ( JpaTransactionManager ) manager1 ).getDataSource();
TEMPLATE1 = new JdbcTemplate( source );
// NOTE: Here, there is no error ... at least, IntelliJ isn't showing any.
source = ( ( JpaTransactionManager ) manager2 ).getDataSource();
TEMPLATE2 = new JdbcTemplate( source );
}
public Map<String, Object> fetchData() {
return TEMPLATE1.queryForList( "..." ); // TODO: something
}
}

您可以实现ApplicationContextAware接口来获取上下文对象,使用此上下文对象即使在静态上下文中也可以获取bean。

public class ApplicationBeansProvider implments ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
}

然后在你的代码中,你可以做一些类似的事情

private final class Repository {
private Repository() {}
private static final JdbcTemplate TEMPLATE;
private static PlatformTransactionManager manager = ApplicationBeansProvider.getBean("transactionManager");

static {
DataSource source =
( ( JpaTransactionManager ) manager ).getDataSource();
TEMPLATE = new JdbcTemplate( source );
}
public Map<String, Object> fetchData() {
return TEMPLATE1.queryForList( "..." ); // TODO: something
}
}

最新更新