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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With