i am trying to write a method in my Entity class before populating the properties of entity class. To Do that i need to call a rest service . I like to bring my resttemplate into my Entity class using Autowired . Is that something possible , If yes how we can do that .
@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.
}
This is the code in Config class
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
CodePudding user response:
Entities belong to the domain layer. It is better to make them not depends on any external framework or library stuff such as RestTemplate
as much as you can. Also, having the domain layer interacts with the external systems directly just does not feel right to me. They should be done in a higher level layer such as service layer. So it is better to have a separate service class like OrderService
to do such logic. You can then easily inject the RestTemplate
into this service class.
If you insist doing it inside the domain model , please checkout this for how to use @Configurable
and AspectJ to do it.