首页 > 解决方案 > 使用依赖注入 Spring 在启动时配置静态字段

问题描述

当我的应用程序启动时,我需要使用依赖注入获得的对象来配置一个类的静态字段。
特别是,我有一个管理通知通道的类,该类应该有一些“默认通道”可以使用,如下所示:

公共类 CustomerNotificationPreference {
    静态列表<NotificationChannel> 默认值 = List.of();
    长身份证;
    列出<NotificationChannel> 频道;
}

一切都适用于非静态字段,但我找不到defaults使用依赖注入配置它的方法。

到目前为止,我尝试过的是以下内容:

@SpringBootApplication(scanBasePackages = {"com..."})
@EnableJpaRepositories("com...")
公共类 MyApp {

    @豆
    无效配置默认频道(
        电报机器人电报机器人,
        JavaMailSender javaMailSender,
        @Value("${telegram-bot.default-chat}") 字符串 chatId,
        @Value("${mail.default-receiver}") 字符串到
    ){
        CustomerNotificationPreference.setDefaults(List.of(
            新的 TelegramNotificationChannel(telegramBot, chatId),
            新的 MailNotificationChannel(javaMailSender, to)
        ));
    }

}

但显然 Spring 不允许这样做,因为 Bean 不能是 void ( Invalid factory method 'configureDefaultChannel': needs to have a non-void return type!)……有没有办法做这种事情?

标签: javaspring-bootdependency-injectionjavabeans

解决方案


您不能直接自动装配静态字段,但您可以在应用程序初始化后使用@PostConstruct或捕获设置静态字段ApplicationReadyEvent

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
    }
    
} 

推荐阅读