[英]Is it possible to set the @Qualifier annotation to a private static variable in a Java class?
我目前正在使用JDBC模板從數據庫中獲取數據。 為此,我創建了一個“靜態”存儲庫類(即標記為“ final”的類,並帶有一個私有構造函數)。 在其中,我嘗試設置兩個私有靜態PlatformTransactionManager
類變量的值。
但是,我的IntelliJ告訴我,類變量的值始終為null,而且我不知道如何解決此問題。
我希望將它們用作靜態構造函數中的局部變量,因為我真正想要的是我將使用PTM准備的JdbcTemplate常量。 由於我不知道該怎么做,因此我嘗試將它們設置為private static final
字段。 但是IntelliJ也不允許這樣做。
為了解決這個問題,我研究了以下線程:
。 。 。 以及關於預選賽的注意事項:
重要筆記:
以下是我的源代碼的示例:
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.