Through this article, I will introduce to you several methods of instantiating beans in Spring through the example code. Let’s take a look at the specific content.
1. Use class constructor to implement instantiation (bean's own constructor)
<bean id = "orderService"/>
2. Use static factory methods to achieve instantiation
<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. Use the instantiation factory method to achieve instantiation (through beans of other entities)
<bean id = "personServiceFactory" class = "cn.itcast.service.OrderFactory"/><bean id = "persionService" factory-bean = "personServiceFactory" material-method = "createOrder"/> public class OrderFactory{ private static OrderService orderService = new OrderService(); private OrderFactory(); public static OrderService createOrderServiceBean{ return OrderService; } }We usually call the BeanFactory or ApplicationContext responsible for loading beans Spring container. Both are loaded with beans through the xml configuration file. Compared with ApplicationContext and BeanFacotry, the main difference is that BeanFacotry is lazy loading, and the bean to be instantiated when gettingBean() is called. If a certain attribute of the bean cannot be injected, an exception will be thrown at this time; and ApplicationContext defaults to instantiating all beans when initializing itself, unless lazy-init="true" is set to the bean, which is conducive to checking whether the dependency attribute can be injected.
In addition, ApplicationContext provides more extension functions, such as international processing of resource files to be loaded and processing of BeanPostProcessor. Therefore, in J2EE applications, we usually choose to use ApplicationContext. Whether using BeanFactory or ApplicationContext, Spring initializes beans in singleton by default.
For initialization of BeanFactory, the following code is usually used:
ClassPathResource resource = new ClassPathResource("beans.xml");BeanFactory factory = new XmlBeanFactory(resource);For initialization of ApplicationContext, it is usually configured in web.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>
Summarize
The above is all the detailed explanation of the code of Spring instantiation beans. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!