Skip to content

Bean scope

  • Default scope: Singleton

Singleton scope

  • Spring Container creates only one instance of the bean
  • It's cached in memory
  • All references to the bean, return the shared reference to the same bean
  • Good for stateless beans!
<beans>
  <bean id="myCoach"
        class="com.hvitoi.springdemo.myCoach"
        scope="singleton">
  </bean>
</beans>
@Component
@Scope("singleton")
public class TennisCoach implements Coach{
  //
}

@Component
@Scope("prototype")
public class TennisCoach implements Coach{
  //
}

Prototype

  • New bean for each container request
  • Prototype scopes do not call the destroy method
<bean id="myCoach"
      class="com.hvitoi.springdemo.TrackCoach"
      scope="prototype">
  <!-- set up constructor injection -->
  <constructor-arg ref="myFortuneService" />
</bean>
// load spring config file
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-beanScope.xml");

// retrieve bean
Coach alphaCoach = context.getBean("myCoach", Coach.class);
Coach betaCoach = context.getBean("myCoach", Coach.class);

// check if they are the same beans
boolean areBeansEqual = (alphaCoach == betaCoach);

// print out the results
System.out.println("\nPointing to the same object: " + areBeansEqual);
System.out.println("\nMemory location for alphaCoach: " + alphaCoach);
System.out.println("\nMemory location for betaCoach: " + betaCoach);

Request

  • Scoped to an HTTP web request

Session

  • Scoped to an HTTP web session

Global-session

  • Scoped to a global HTTP web session