Search code examples
springspring-beanstatelessservice-layer

Stateless Service Layer in Spring


These days im working on a Web project and i just want to clarify couple of things regarding Spring bean scopes and best practices for Spring based developments. Here i am using a scenario using a sample code

I have a Web Controller as below

@Controller
Public class JobController{
   private JobService jobService;

   @Autowired
   public void setJobService(JobService jobService ) {
       this.jobService = jobService ;
    }

    public void run(){
         Job job = new Job();
         -- Setting the properties for the Object

        jobService.run(job);
    }

}

Then I have the Service as below

@Service
Public class JobService {
     public void run(Job job){
         -- perform the business logic
    }
}

In Here i want to make the JobService class stateless so i can define JobService as singleton hence reduce the unnecessary object creation. As per my understanding in-order make a class stateless we do not want to keep instance properties.In This scenario i pass different Job objects to the service. Does this make this JobService statefull because JObservice process different different job objects? Can you please help me to understand

Thanks, Keth


Solution

  • Passing different objects does not make your service stateful.

    Consider this for example.

    @Service
    Public class JobService {
      private Job currentJob;
      public void setJob(Job job) {
         currentJob = job;
      }
      public void run(){
          -- perform the business logic on currentJob
      }
    }
    

    This would make the bean 'stateful' and cause unexplained behavior.

    The execution of the method in your singleton by multiple controller/threads will not collide and can be assumed to be safe.