Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Autowired vs using 'new' keyword to create Object [closed]

I am learning Spring and building some experiment application. I am confused on where to use @Autowired for creating the Object.

I get the part that it promotes loose coupling and also does create a new Object Every time as opposed to what 'new' keyword do.

But what should we do for the Third Party Objects which we need to use in our Application. For example I am consuming a rest API for that I need to Initialise three Classes , something like this

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
restTemplate.exchange(url, HttpMethod.POST, entity, String.class); 

This chunk of code is creating new Objects for RestTemplate, HttpHeaders and HttpEntity. With this code it will create three new objects everytime I call the rest API. Is it the correct approach or should I mark them @Autowired. Please elaborate.

like image 627
Tushar Avatar asked Mar 16 '23 16:03

Tushar


1 Answers

The typical use of @Autowire is to automatically fill a property, when initializing a bean, with a singleton dependency. It does not matter if it's your code or a Third Party class. You need to consider if it is part of your program's logic or if it is really a dependency that should be initialized once and reused.

If your RestTemplate needs to have the same initialization before each exchange then you can consider using @Autowire and initialize the bean in Spring's configuration. In this sense it would be similar to a DataSource, for example. But if you see it as an utility class that is used as part of the program's logic (like a connection or a file) then do not consider it for @Autowire. It will make your program more complex without a significant gain.

like image 200
m4ktub Avatar answered Apr 28 '23 05:04

m4ktub