gpt4 book ai didi

java - Spring中枚举中如何 Autowiring 服务

转载 作者:行者123 更新时间:2023-12-02 01:59:37 24 4
gpt4 key购买 nike

我想像下面的代码一样在枚举中自动连接服务。

public enum TopupChargeService {
TYPE1{
public Response fun() {
return new ServiceRepo().getService().func1();
}
},
TYPE2{
public Response fun() {
return new ServiceRepo().getService().func2();
}
};
public abstract Response fun();
@Component
public static class ServiceRepo {
private Service service;
public Service getService() {
return service ;
}
public ServiceRepo () {
service = new ServiceImpl();
}
}
}

服务代码类似于以下代码。

@Service
public class ServiceImpl implements Service {

@Autowired
private RestTempalte restTemplate;

Response fun1(){
// use restTemplate in this fun
}

Response fun2(){
// use restTemplate in this fun
}

}

我还将restTemplate定义为配置类中的bean。但restTemplate 为空。

我的问题:1- 调用服务电话的方式正确吗? 2-为什么restTemplate为空?

最佳答案

new ServiceRepo()

您正在使用构造函数创建存储库,这就是 Spring 无法向此实例注入(inject)任何内容的原因。为了正确创建 bean,请尝试使用 ApplicationContext 创建 bean 实例。

此外,我建议您不要在这种情况下使用枚举。枚举更像是静态常量,它们不应该带来行为。考虑用 Spring bean 替换此枚举。

关于java - Spring中枚举中如何 Autowiring 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51818378/

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