java - 使用依赖注入 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!
)……有没有办法做这种事情?
解决方案
您不能直接自动装配静态字段,但您可以在应用程序初始化后使用@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
}
}
推荐阅读
- wordpress - 在 WordPress Gutenberg Block Development 中使用错误的片段标签
- python-3.x - 如何剥离拖尾空间?
- java - (JAVA) 数组中整数的加法
- javascript - 如何验证具有多个选项卡的表单?
- angular - Angular - RxJS - Observable 和方法返回
- amazon-web-services - 访问 S3 中数据的权限不足 - AWS
- html - 背景过滤器会导致字体上不需要的“抗锯齿”
- amazon-web-services - EC2实例向外发出请求时如何查找EC2实例使用的IP地址
- mysql - 尝试将变量作为表名和值插入时出现 mysql 语法错误
- javascript - 带有循环的 Promise.all() 并将结果同时存储到 Javascript 中的 JSON 对象