簡體   English   中英

是否可以將@Qualifier批注設置為Java類中的私有靜態變量?

[英]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也不允許這樣做。

為了解決這個問題,我研究了以下線程:

以及關於預選賽的注意事項:

重要筆記:

  • 我正在處理的項目沒有XML配置文件。 項目中有[*] Config個文件可以處理配置。
  • 需要注意的另一件事是,我一般不太了解注釋(例如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
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM