Reputation: 21
My code is as below . Here i use a local variable to store data and return it to the controller method. Whenever the scheduled post construct method runs i use a temporary list. But i read somewhere that spring service should not be having state. What is a better way to do this?
@Service
public class AppService
{
private List<String> responseList = new ArrayList<>();
@PostConstruct
@Scheduled(every 2hours)
public void getData()
{
//get data from another third party REST API endpoint and populate a temporary list
//Once all data is fetched set temp list as mainList
this.responseList = tempList;
}
public List<String> getResponse()
{
return this.responseList;
}
}
Upvotes: 0
Views: 4123
Reputation: 3491
Shahul,
It depends on two factors: (a) how the service is going to be used (i.e. deployed and operated) and (b) where is the data for the responseList
is going to come from.
First, as @Michael said, you should always cite your sources. On Stackoverflow, it can help people see if you read wrong or outdated information or simply misunderstood the source and, eventually, help you more effectively. Indeed, https://spring.io/microservices states (emph. mine):
The small, stateless nature of microservices makes them ideal for horizontal scaling.
So here is the key to the first factor: if you want to make a microservice and scale it, it better be stateless. However, @Service
in Spring defines a Service Component and it's javadocs state:
Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state."
If you study the javadocs for other @Component
descendants, you will see that @Repository
has the following description:
Indicates that an annotated class is a "Repository", originally defined by Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects".
I recommend you read more about Repositories and Spring Persistence in general. The answer for factor B will tell you what kind of persistence method to use.
Upvotes: 2