簡體   English   中英

使用依賴注入 Spring 在啟動時配置 static 字段

[英]Configure static field on boot with dependency injection Spring

當我的應用程序啟動時,我需要使用使用依賴注入獲得的對象來配置 class 的 static 字段。
特別是,我有一個管理通知通道的 class ,並且 class 應該有一些“默認通道”可以使用,如下所示:

public class CustomerNotificationPreference {
    static List<NotificationChannel> defaults = List.of();
    Long id;
    List<NotificationChannel> channels;
}

一切都適用於非靜態字段,但我找不到使用依賴注入配置defaults的方法。

到目前為止,我嘗試過的是以下內容:


@SpringBootApplication(scanBasePackages = {"com..."})
@EnableJpaRepositories("com...")
public class MyApp {

    @Bean
    void configureDefaultChannel(
        TelegramBot telegramBot,
        JavaMailSender javaMailSender,
        @Value("${telegram-bot.default-chat}") String chatId,
        @Value("${mail.default-receiver}") String to
    ){
        CustomerNotificationPreference.setDefaults(List.of(
            new TelegramNotificationChannel(telegramBot, chatId),
            new MailNotificationChannel(javaMailSender, to)
        ));
    }

}

但顯然 Spring 不允許這樣做,因為 Bean 不能是無效的( Invalid factory method 'configureDefaultChannel': needs to have a non-void return type! )......有沒有辦法做這種事情?

您不能直接自動裝配 static 字段,但您可以在使用@PostConstruct初始化應用程序或捕獲ApplicationReadyEvent后設置 static 字段

public class MyApp {

    @Autowired
    TelegramBot telegramBot;

    @Autowired
    JavaMailSender javaMailSender

    @Value("${telegram-bot.default-chat}")
    String chatId;

    @Value("${mail.default-receiver}") 
    String to;

    @PostConstruct
    void setDefaults() {
        CustomerNotificationPreference.setDefaults(List.of(
            new TelegramNotificationChannel(telegramBot, chatId),
            new MailNotificationChannel(javaMailSender, to)
        ));
    }

    // OR

    @EventListener(ApplicationReadyEvent::class)
    void setDefaults() { 
        // same code as above
    }
    
} 

暫無
暫無

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

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