Reputation: 1717
I have a Spring-Boot app. with this abstract controller
public abstract class ElCorDeLaCiutatController {
static Double price = 0.0;
@Autowired
PriceService priceService;
@Scheduled(fixedRate = 1000 )
private void updatePrice() throws DataAccessException, SQLException, ClientProtocolException, IOException {
price = getPrice();
}
}
Where I want to update the price every second, because the price is a common value shared for all controllers, but I see that this method is called something like 14 times each second...
maybe for all the controllers that extends this abstract controller?
Is there a way to avoid this?
Upvotes: 0
Views: 1794
Reputation: 7071
Well extending from that class might cause problems. Also having a static field like that to share the value between the classes is not the greatest.
I think a better approach would be to move the price to the price service. It is a static value anyway so it is the same for all Controllers. Just move it to the service and move the scheduled task there. Let the service take care of that price (and all other parts of the business logic) and in the controllers get the current value when you need it. You also separate keep the different purpose of the different layers like that.
Something like:
class PriceService{
Double price = 0.0;
getCurrentPrice(){
return price;
}
@Scheduled
updatePrice(){
.. do something here
}
}
And in the controllers when you need the current price you just use priceService.getCurrentPrice();
from the injected service without any static fields and without maintaining state in controllers
Upvotes: 3
Reputation: 585
I'd put that price and schedule in a separated bean and reference it as a static member of ElCorDeLaCiutatController.
Upvotes: 0