繁体   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