My application is listening to an exchange (using rabbitMQ), expecting to receive some API data and then should redirect it to the relevant place.
I'm using rxJava to subscribe on these changes, when the purpose is to open a new thread and send the request by creating RestClient each time -> it will receive the data, parse it, send it and then send the response back to queue.
My problem is that I want each time to create a new instance of my RestClient. Thought of using Springs Scope annotation : @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) but can't seem to understand how to use it and what will be the difference if I use new RestClient each time.
Can you please explain the advantage of using getBean over using new?
Here is the code:
class MyManager {
@Autowired
private WebApplicationContext context;
....
...
...
@PostConstruct
myListener.subscribeOn(Schedulers.computation()).subscribe(this::handleApiRequest);
private void handleApiRequest(ApiData apiData){
// Option 1:
RestClient client = new RestClient();
client.handleApiRequest(apiData);
//Option 2:
// use somehow the prototype?
RestClient x = (RestClient)context.getBean("restTest")..
}
}
@Service
//@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) //NEEDED??
class RestClient {
private String server;
private RestTemplate rest;
private HttpHeaders headers;
ResponseEntity<String> responseEntity;
@PostConstruct
private void updateHeaders() {
headers.add(Utils.CONTENT_TYPE, Utils.APPLICATION_JSON);
headers.add(Utils.ACCEPT, Utils.PREFIX_ALL);
}
public void handleApiRequest(ApiData apiRequest) {
sendRequest(apiRequest); //implemented
sendResponse(); //implemented
}
}
@Bean(name = "restTest")
@Scope("prototype")
public RestClient getRestTemplate() {
return new RestClient();
}