Spring bean instantiation method code details, springbean
This article introduces several methods for Spring bean instantiation through the instance code. Let's take a look at the specific content.
1. Implement instantiation using the class Constructor (bean self constructor)
<bean id = "orderService" class="cn.itcast.OrderServiceBean"/>
2. Use the static factory method for 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 implement instantiation (through bean of other entities)
<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 call BeanFactory or ApplicationContext that loads beans as Spring containers. Both of them load beans through the xml configuration file. The main difference between ApplicationContext and BeanFacotry is that BeanFacotry is delayed loading, and the get bean is instantiated only when getBean () is called. If a Bean property cannot be injected, an exception is thrown. By default, ApplicationContext instantiates all beans when initializing itself, unless lazy-init = "true" is set for the bean, this helps to check whether the dependent attributes can be injected.
In addition, ApplicationContext provides more extension functions, such as internationalization of the resource files to be loaded and BeanPostProcessor. Therefore, in J2EE applications, we usually choose ApplicationContext. Whether BeanFactory or ApplicationContext is used, Spring initializes beans in singleton mode by default.
For BeanFactory initialization, the following code is usually used:
ClassPathResource resource = new ClassPathResource("beans.xml");BeanFactory factory = new XmlBeanFactory(resource);
For ApplicationContext initialization, 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>
Summary
The above is all the details about how to use Spring to instantiate bean. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!