There is some different styles people write codes and something that caught my attention was that some people did not use service class and only the controller class when writing the code. And I was wondering why do some people use service class and some people don't. And as a somewhat beginner should i learn one way style of coding or adapt and try to learn different styles?
I wouldn't call it a coding style, rather an architecture.
Putting business logic in controllers is okay if you have a very simple application with very few interwoven parts, and no advanced features like transaction management.
In a more complex application, to fulfill a user request controllers must often get information from multiple sources, or perform operations on multiple business models. For instance, a teacher might request the names of all students in a particular class they teach. The controller must retrieve the teacher's class and it must retrieve the student information of each student in the class.
If the controller did all this work by itself, it would lead to very large controller actions with very little code reuse. Instead, we write services that are responsible for different reusable operations. We make a service that is responsible for student registration, and we make a service that is responsible for keeping track of what students are enrolled in which classes. The class service can also call into the student service to implement its behavior.
What's left for the controller to do? The controller acts as the starting point of transactions and it aggregates information from different services and converts this information to response messages. Basically, it does the non-reusable stuff that is specific to the individual user request.
So how complex does an application need to be before you start using service classes and delegate to them from your controllers? In my experience, not so complex. Nine out of ten times, the application starts simple and then needs to get updated and the controllers balloon and you wish you had started by writing reusable services from the start. This is fine, you can refactor code. In my experience though, people will often put off refactoring code until the situation has become unworkable.
My advice is to write services every time and keep controllers as small as possible. Note that my entire post applies to any web service, not just to those using Spring.