when is a spring bean instantiated

后端 未结 7 1408
借酒劲吻你
借酒劲吻你 2020-12-08 07:26
ApplicationContext ctx = new ClassPathXmlApplicationContext(
    \"com/springinaction/springidol/spring-idol.xml\");
Performer performer = (Performer) ctx.getBean(\"         


        
相关标签:
7条回答
  • 2020-12-08 07:42

    Assuming the bean is a singleton, and isn't configured for lazy initialisation, then it's created when the context is started up. getBean() just fishes it out.

    Lazy-init beans will only be initialised when first referenced, but this is not the default. Scoped beans (e.g. prototype-scoped) will also only be created when first referenced.

    0 讨论(0)
  • 2020-12-08 07:42

    For reference, see

    • Lazy-initialized beans and
    • Bean scopes

    Here's a brief description of when beans are created:

    • A singleton bean (which is the default scope) that does not have the lazy-init property set to true (default is false) is constructed when the application context is created
    • A singleton bean that does have the lazy-init property set to true is constructed when it is first requested
    • A bean set in any other scope is created when it is first requested (for that scope).
    0 讨论(0)
  • 2020-12-08 07:44

    By default, Spring ApplicationContext eagerly creates and initializes all ‘singleton scoped‘ beans during application startup itself. ApplicationContext makes the bean available in BeanFactory. getBean() returns the instance of the bean.

    0 讨论(0)
  • 2020-12-08 07:48

    It depends what is the scope of the bean you are calling with getBean() method. If it is 'Singleton', it is pre-instantiated by the ApplicationContext.

    If you are using BeanFactory as an IOC Container, then it uses lazy initialization and the beans will be instantiated only when you call the getBean() method.

    This is an advantage of ApplicationContext over BeanFactory that it solves Circular Dependency problem.

    0 讨论(0)
  • 2020-12-08 07:53

    According to Spring documentation,

    The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup.

    Also, you can set them to load lazily.

    0 讨论(0)
  • 2020-12-08 08:00

    By default it's created when the context is started up but the order depends on dependencies. If we have the following classes :

    @Component
    public  class A{
    
    }
    
    @Component
    public class B{
        @Autowired
        A a;
    
    }
    

    Class A will be created before class B because class B depends on class A.

    0 讨论(0)
提交回复
热议问题