Details of the way Spring instantiates bean

  • 2020-12-18 01:50:42
  • OfStack

This article introduced you to some of the ways Spring instantiates bean through example code, so let's take a look at the details.

1. Instantiate using class constructors (bean's own constructor)


<bean id = "orderService" class="cn.itcast.OrderServiceBean"/> 

2. Instantiate using static factory methods


<bean id = "personService" class = "cn.itcast.OrderFactory" factory-method   = "createOrder"/>
public class OrderFactory{
  private static OrderFactory orderFactory = new OrderFactory();
  private OrderFactory();
  public static OrderFactory createOrder(){
     return OrderFactory;  
  } 
}

3. Instantiate using the instance chemical plant method (via bean of another entity)


<bean id = "personServiceFactory" class = "cn.itcast.service.OrderFactory"/>
<bean id = "persionService" factory-bean = "personServiceFactory" foctory-method = "createOrder"/>
public class OrderFactory{
  private static OrderService orderService = new OrderService();
  private OrderFactory();
  public static OrderService createOrderServiceBean{
    return OrderService;
  }
    
}

We usually refer to the BeanFactory or ApplicationContext that is responsible for loading bean as the Spring container. Both load bean via the xml configuration file. The main difference between ApplicationContext and BeanFacotry is that BeanFacotry is lazy-loaded and the bean to get is instantiated when getBean() is called. If one of Bean's attributes cannot be injected, an exception will be thrown. By default, ApplicationContext instantiates all bean when it initialises itself, unless bean is set to ES32en-ES33en ="true", which helps to check whether the dependent properties can be injected.

In addition, ApplicationContext offers many more extensions, such as internationalization of the resource files to be loaded, and BeanPostProcessor, so in J2EE applications, ApplicationContext is usually the preferred option. Whether using BeanFactory or ApplicationContext,Spring initializes bean as singleton by default.

For the initialization of BeanFactory, the following code is usually used:


ClassPathResource resource = new ClassPathResource("beans.xml");
BeanFactory factory = new XmlBeanFactory(resource);

For the initialization of ApplicationContext, it is usually configured in ES54en.xml:


<context-param>  
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:conf/Appcontext.xml
    </param-value>
</context-param>
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

conclusion

That's the end of this article on Spring's way of instantiating bean in code detail, and I hope you found it helpful. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: