0

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

keth
  • 793
  • 2
  • 11
  • 36
  • By default in Spring all spring beans are singleton unless specified otherwise. So if you have @Service on JobService by default it is a singleton – pvpkiran Nov 21 '17 at 12:43
  • @pvpkiran thanks for the reply. Yes Spring beans are singleton by default. But do we need to control the logic inside the service class to be singleton. Even we marked as singleton is there any way that the developer can violate the singleton behavior? – keth Nov 21 '17 at 12:51

1 Answers1

1

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.

zatopek
  • 333
  • 2
  • 8
  • thanks @zatopek for the reply, Do not we need to explicitly synchronize these service layer methods in Spring if it is a singleton bean? – keth Nov 21 '17 at 13:11
  • 1
    Not needed if they are not accessing any shared resources, but if they do access variables beyond their method scope, that will need to be evaluated case by case. – zatopek Nov 21 '17 at 14:47