gpt4 book ai didi

java - 如何从另一个类获取服务?

转载 作者:行者123 更新时间:2023-12-01 16:50:15 24 4
gpt4 key购买 nike

我正在使用 Spring-Boot 创建电报机器人。我有 AscratState 类:

public abstract class AbstractState {
boolean isInputIndeed = Boolean.FALSE;
public abstract void handleInput(BotContext context);
//another parts
}

还有扩展

@Slf4j
public class AgeInputState extends AbstractState {

@Autowired
ClientService clientService;

public AgeInputState(boolean isInputIndeed) {
super(isInputIndeed, State.AGE_INPUT);
}

@Override
public void handleInput(BotContext context) {
context.getClient().setAge(Integer.parseInt(context.getInput()));
clientService.updateUser(context.getClient());
}
}

但是我对 ClientService 遇到了麻烦。我需要在类上添加哪些注释才能 Autowiring 该字段?

最佳答案

由于此类有一个接受 boolean 值的构造函数,我假设您需要很多它们。 p>

如果您直接调用此构造函数,Spring 将不知道您想要将它们加载为 spring bean。因此,通过某种工厂来创建这些将是一种方法。像这样的东西:

@Configuration
public class AgeInputStateFactory {

private @Autowired ClientService clientService;

@Bean
@Scope("prototype") // Makes a new one each time...
public AgeInputState create(final boolean isInputIndeed) {
return new AgeInputState(this.clientService, isInputIndeed);
}
}

以及设计的AgeInputState构造函数,采用ClientService字段。

public class AgeInputState extends AbstractState {
private final ClientService clientService;

// Package private constructor so that no one outside
// of this package will call it. This means you can
// (try your best to) limit the construction to the
// factory class.
AgeInputState(final ClientService clientService,
final boolean isInputIndeed) {
super(isInputIndeed, State.AGE_INPUT);

this.clientService = clientService;
}
}

然后您要做的就是在任何需要创建这些 AgeInputState Object 的地方,您都会 @Autowire AgeInputStateFactory 实例,并在需要时调用 create 方法。

关于java - 如何从另一个类获取服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61704998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com