繁体   English   中英

如何使用 autowired 在实体 class 中获取 Resttemplate Bean

[英]How to get Resttemplate Bean in Entity class using autowired

在填充实体 class 的属性之前,我正在尝试在我的实体 class 中编写一个方法。 为此,我需要调用 rest 服务。 我喜欢使用 Autowired 将我的 resttemplate 带入我的实体 class。 这有可能吗,如果是的话,我们怎么能做到这一点。

@Entity
@Table(name = "IC_ORDER")
public class ICOrder implements Serializable {

@Id
@GenericGenerator(name = "UUIDGenerator", strategy = "uuid2")
@GeneratedValue(generator = "UUIDGenerator")
@Type(type = "uuid-char")
UUID id;

@Transient
@Autowired
private RestTemplate restTemplate;

@SneakyThrows
int start(Context context,String userId) {

//restTemplate.postForEntity // Trying to call a rest service here . But getting 
restTemplate as null , Want to avoid new Resttemplate here.

}

这是配置 class 中的代码

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();

}

实体属于领域层。 最好使它们尽可能不依赖于任何外部框架或库的东西,例如RestTemplate 此外,让域层直接与外部系统交互对我来说并不合适。 它们应该在更高级别的层中完成,例如服务层。 所以最好有一个单独的服务 class 像OrderService来做这样的逻辑。 然后,您可以轻松地将RestTemplate注入此服务 class。

如果您坚持在域 model 内执行此操作,请查看内容以了解如何使用@Configurable和 AspectJ 执行此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM