我正在尝试在 @Configuration
类中使用 @Autowired
变量,其中在方法中使用 @Bean
创建 bean 。然而,我需要用来创建 bean 的组件是 null
。
@Autowired
private JDAListener listener;
@Bean
public ShardManager shardManager() throws LoginException, IllegalArgumentException {
DefaultShardManagerBuilder builder = DefaultShardManagerBuilder.createDefault(this.botToken)
.enableIntents(GatewayIntent.GUILD_MEMBERS)
.setStatus(OnlineStatus.IDLE)
.setShardsTotal(this.totalShards)
.addEventListeners(Arrays.asList(this.listener)); //throws Exception
return builder.build();
}
我得到的异常如下:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'config':
Unsatisfied dependency expressed through field 'shardManager'; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'shardManager' defined in class path resource [dev/teamnight/nightbot/Config.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [net.dv8tion.jda.api.sharding.ShardManager]: Circular reference involving containing bean 'config' - consider declaring the factory method as static for independence from its containing instance. Factory method 'shardManager' threw exception;
nested exception is java.lang.IllegalArgumentException: listeners may not be null
最佳答案
我假设代码片段是某种配置的一部分(用@Configuration
注释的东西,甚至可能是@SpringBootApplication
)。
在这种情况下:
- 使
JDAListener
也由 Spring 容器管理。 - 通过将参数传递给
shardManager
方法,将JDAListener
bean 实例注入(inject)分片管理器
您最终将得到如下所示的代码:
@Configuration
public class MyConfiguration {
@Bean // now jda listener is managed by spring!
public JDAListener jdaListener() {
return new JDAListener();
}
@Bean // note the parameter to the method
public ShardManager shardManager(JDAListener jdaListener) throws LoginException, IllegalArgumentException {
DefaultShardManagerBuilder builder =
DefaultShardManagerBuilder.createDefault(this.botToken)
.enableIntents(GatewayIntent.GUILD_MEMBERS)
.setStatus(OnlineStatus.IDLE)
.setShardsTotal(this.totalShards)
.addEventListeners(Arrays.asList(jdaListener)); //throws Exception
return builder.build();
}
}
关于java - Spring Autowired 组件在 bean 方法中为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62398103/