Spring singleton vs prototype scope

Jun 13, 2014 00:00 · 284 words · 2 minute read Java Spring

What is singleton scope?

Singleton is a default scope in spring application so its means that there is only one instance of our bean is available through the project by default.

You might still have more than 1 instance per jvm if you are running more than 1 project with your jvm.

How to do it ?

To setting it up in a java project its really straightforward all you need to do is adding the annotation scope to your config file. Also you need add the AOP jar file to your class path.

Add annotation

annotation

@Configuration
@ComponentScan({"com.inadram"})
public class AppConfig {
 
    @Bean(name = "customerService")
    @Scope("singleton")
    public CustomerService getCustomerService() {
        return new CustomerServiceImplementation();
    }
 
    @Bean(name = "customerRepository")
    public CustomerRepository getCustomerRepository() {
        return new hibernateRepositoryImplementation();
    }
}

The “@Scope(‘singleton’)” will make sure that there should be only one instance of customerServiceImplementation class is available in the project.

Add AOP Jar file to your class path.

Download the AOP jar file from the Spring library and adding it your project. You do not need it when you are using xml configuration .

To prove it we can print out the instances of this class and compare their signature together.

customerService

CustomerService service = appContext.getBean("customerService", CustomerService.class);
System.out.println(service);
CustomerService service2 = appContext.getBean("customerService", CustomerService.class);
System.out.println(service2);

What is prototype scope ?

Prototype is the exact opposite way of the singleton. It will guarantee that we have one instance per request in the project.

How to do it?

Its steps are pretty much similar to singleton. All you need to do is just change the scope annotation to “prototype” in the config file.

prototype scope

@Scope("prototype")

Download

Feel free to download the source code of this comparison from my gitHub.