添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Don't lose your work!

Create a free account to track your progress, so you won't miss a thing. Join for free

In earlier lessons, you learned that the IoC container manages the lifecycle of Spring beans. Let's explore how a bean's scope influences its instantiation, management, and eventual destruction. This lesson will discuss the distinct behavior of each Spring bean scope, helping you make informed decisions about when to use each.

Bean Scopes in Spring

In the Spring Framework, there are different types of bean scopes available. The scope of a bean mainly defines the lifecycle and visibility of a given bean within the context it is being used. You use the Spring Framework in a declarative manner and as a result, can control each bean's lifecycle according to your needs.

There are six kinds of beans supported in the Spring Framework:

  • Singleton - One single bean instance per Spring IoC container.
  • Prototype - A new bean instance each time when requested.
  • Request - A single bean per HTTP/HTTPS(Web) request.*
  • Session - A single bean instance per HTTP/HTTPS session.*
  • Global Session - A single bean instance per HTTP/HTTPS global session.*
  • Application - A single bean per lifecycle of a ServletContext.*
  • Note: * Only valid in the context of a web-aware Spring ApplicationContext. (source)

    This idea of "bean scopes" allows you to define beans that match your applications' feature set and functionality. For instance, it is quite possible and quite common that a new bean of a given type will be needed for each user session on your web application. However, there could very well be no need for other beans to be "session-based", so they could/should be singletons to reduce space/time/memory continuum. Managing this type of process manually would be a real pain. Fortunately, Spring takes care of this for you.

    Singleton Scope

    As the name suggests, with a singleton bean , only a single instance of a given type will exist. No matter how many times you ask for it, the IoC container will always return the exact same bean instance. For performance gain, the bean will be cached as well, so it can be retrieved faster next time you need it. Let's see that in Action!

    Example Location:
    com.codingnomads.corespring.examples.beanscopes.singleton

    SpringBean Class

    public class SpringBean {
        public SpringBean() {
            System.out.println(
                  "-----Hey, I'm a Spring bean, not a String bean!-----");
    

    In this example, a simple constructor prints to the console. This will help to highlight the singleton concept, by ovserving that regardless of how many beans are requested, the SpringBean constructor is invoked only once.

    Configuration Class

    @Configuration
    public class SingletonDemoConfig {
        @Bean
        @Scope(value = "singleton")
        public SpringBean springBean() {
            return new SpringBean();
    

    Main Class

    @SpringBootApplication
    public class SingletonDemo {
        public static void main(String[] args) {
            AnnotationConfigApplicationContext ctx = 
                    new AnnotationConfigApplicationContext();
            ctx.register(SingletonDemoConfig.class);
            ctx.refresh();
            SpringBean springBean1 = ctx.getBean(SpringBean.class);
            System.out.println("Hash code: " + springBean1.hashCode());
            SpringBean springBean2 = ctx.getBean(SpringBean.class);
            System.out.println("Hash code: " + springBean2.hashCode());
            ctx.close();
    

    Output:

    -----Hey, I'm a Spring bean, not a String bean!-----
    Hash code: 1585239756
    Hash code: 1585239756
    

    Notice how the constructor is being called only once ("Hey..." only prints once), even though you have referenced the SpringBean bean twice. Also, both of your referenced objects springBean1 and springBean2 have the same hash code. As you've learned in your previous Java courses, objects with the same hashCode() return are considered equal. So they are the same object. It's a Singleton!

    Note: By default, all beans are scoped as singleton, so you can remove the scope from your config and expect the same output. In the Learn by Doing below, you will give this a try.

    Package: corespring.examples.beanscopes.singleton

  • Inside SingletonDemoConfig, comment out the @Scope annotation.
  • Run the application again.
  • Inspect the hash code of each bean in the console, yep still a Singleton :)
  • Prototype Scope

    As you may have guessed, when using the prototype scope, the Spring IoC container returns a new object each time you ask for one. This is vastly different behavior than that of a Singleton.

    Example Location:
    com.codingnomads.corespring.examples.beanscopes.prototype

    Your SpringBean class remains the same:

    public class SpringBean {
        public SpringBean() {
            System.out.println(
                  "-----Hey, I'm a Spring bean, not a String bean!-----");
    

    Configuration Class:

    @Configuration
    public class PrototypeDemoConfig {
        @Bean
        @Scope(value = "prototype")
        public SpringBean springBean() {
            return new SpringBean();
    

    Only one change here, @Scope(value = "prototype").

    Main Class:

    @SpringBootApplication
    public class ProtoTypeDemo {
        public static void main(String[] args) {
            AnnotationConfigApplicationContext ctx = 
                    new AnnotationConfigApplicationContext();
            ctx.register(PrototypeDemoConfig.class);
            ctx.refresh();
            SpringBean springBean1 = ctx.getBean(SpringBean.class);
            System.out.println("Hash code: " + springBean1.hashCode());
            SpringBean springBean2 = ctx.getBean(SpringBean.class);
            System.out.println("Hash code: " + springBean2.hashCode());
            ctx.close();
    

    Output:

    -----Hey, I'm a Spring bean, not a String bean!-----
    Hash code: 1680503330
    -----Hey, I'm a Spring bean, not a String bean!-----
    Hash code: 1345900725
    

    So what do you see?

    The constructor was called two times as you request two instances of SpringBean.

    The objects each have a different hash code, hence they are the completely different objects.

    Learn by Doing

    Package: corespring.examples.beanscopes.prototype

  • Create another simple POJO similar to SpringBean.
  • Declare a prototype bean of this class inside PrototypeDemoConfig.
  • In the bootstrapping class, create two objects from this bean. Print the hash code of each to the console.
  • Please push your work to GitHub when you're done.

    Request / Session / Global Session / Application

    These scopes are only valid in the context of Spring Web Applications. You will learn more about them in later sections, but they are pretty simple as their names suggest:

    Request Scope is per HTTP request, and all HTTP requests are independent of each other.

    Session Scope is per user session. You can retrieve user session state from the IoC container according to your needs.

    Global Session Scope can be used in certain web application contexts, such as portlet applications, providing a shared scope across all portlet sessions within the same application context.

    Application Scope is used to share a single bean instance across multiple servlet-based applications running in a single ServletContext.

    Mentorship Makes the Difference!

    You don't have to learn alone. Join the CodingNomads' Mentorship Bootcamp Program and get:

  • A team of mentors and advisors dedicated to your success
  • Weekly 1-on-1 screen share meetings with your professional mentor
  • Constant, personal, in-depth support 7 days a week via Discord
  • Accountability, feedback, encouragement, and success
  • Summary: Spring Framework Bean Scopes

    There are six kinds of bean scopes supported in the Spring Framework:

  • Singleton - one single bean instance per Spring IoC container.
  • Prototype - A new bean instance each time when requested.
  • Request - A single bean per HTTP/HTTPS(Web) request.
  • Session - A single bean instance per HTTP/HTTPS session.
  • Global Session - A single bean instance per HTTP/HTTPS global session.
  • Application - A single bean per lifecycle of a ServletContext.
  • Bean scopes allow you to define beans that match the feature set and functionality of your applications.
  •