SPRING Gets the Bean way (beanfactory and ApplicationContext) _spring

Source: Internet
Author: User

The Bean Factory (com.springframework.beans.factory.BeanFactory) is the core interface of the spring framework, providing a high-level IOC configuration mechanism. Beanfactory makes it possible to manage different types of Java objects, The application context (Com.springframework.context.ApplicationContext), based on Beanfactory, provides more application-oriented functionality, provides internationalization support and framework event systems, and facilitates the creation of practical applications. We generally call beanfactory the IOC container, while the ApplicationContext is called the application context. But sometimes, for the sake of convenience, we also call ApplicationContext the spring container.

For both purposes, we can make a simple distinction: beanfactory is the infrastructure of the spring framework, facing spring itself; ApplicationContext for Development A who uses the spring framework,  In almost all applications we use the ApplicationContext instead of the underlying beanfactory. Beanfactory Introduction

Spring provides a variety of implementations for beanfactory, and the most common is xmlbeanfactory. The Beanfactory interface is located at the top of the class structure tree, and its main method is Getbean (String beanname), which returns the function of the bean,beanfactory of a particular name from the container, expanding through other interfaces.

code example:
Beans.xml:Car configuration file <?xml version= "1.0"  encoding= "UTF-8"  ?> <beans xmlns= "http:/" /www.springframework.org/schema/beans "    xmlns:xsi=" http://www.w3.org/2001/ Xmlschema-instance "    xmlns:p=" http://www.springframework.org/schema/p "     xsi:schemalocation= "Http://www.springframework.org/schema/beans          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "> Modified              <bean id= "Car1"  class= "Com.baobaotao.Car" 08                 p:brand= " Red Flag CA72 "                p: Color= "BLACK"                 p: Maxspeed= "&NB"Sp;/> </beans>

Java calling code: 1 resourcepatternresolver resolver = new Pathmatchingresourcepatternresolver (); 2 Resource res = Resolver.getresource ("Classpath:com/coder/beanfactory/beans.xml"); 3 beanfactory bf = new Xmlbeanfactory (res); 4 Car car = Bf.getbean ("Car", car.class); 5 System.out.println ("Car bean are ready for use!");

Xmlbeanfactory Loads the spring configuration information by resource and launches the IOC container, which can then be retrieved from the IOC container through the Beanfactory#getbean (Beanname) method. When you start the IOC container by beanfactory, the bean defined in the configuration file is not initialized, and the initialization action occurs at the first call. For a single instance (singleton) bean, beanfactory caches the bean instance, so the second use of Getbean () gets the bean instance directly from the cache of the IOC container.

Spring provides a buffer for the instance bean in the Defaultsingletonbeanregistry class, a cache that is implemented with HashMap, and a single instance of the bean saved in this hashmap with a Beanname key. ApplicationContext Introduction

The main implementation class for ApplicationContext is Classpathxmlapplicationcontext and filesystemxmlapplicationcontext, which loads the configuration file by default from the Classpath. The latter defaults to loading the configuration file from the filesystem, let's take a look at ApplicationContext's Class inheritance system:

Similar to beanfactory initialization, the initialization of ApplicationContext is simple:
If the configuration file is placed under the Classpath, the user can use the Classpathxmlapplicationcontext implementation class first: 1 ApplicationContext ctx = new Classpathxmlapplicationcontext ("Com/coder/context/beans.xml");

For Classpathxmlapplicationcontext, "Com/coder/context/beans.xml" equates to "Classpath:com/coder/context/beans.xml".
If the configuration file is placed under the path of the file system, the Filysystemxmlapplicationcontext implementation class can be prioritized: 1 applicationcontext ctx = new Filesystemxmlapplicationcontext ("Com/coder/context/beans.xml");

For Filesystemxmlapplicationcontext, "Com/coder/context/beans.xml" equates to "File:com/coder/context/beans.xml".
You can also specify a set of profiles, and spring automatically "consolidates" multiple profiles into a single configuration file in memory, as follows: 1 ApplicationContext ctx = new Classpathxmlapplicationcontext (new string[]{"Conf/beans1.xml", "Conf/beans2.xml"});

After getting the ApplicationContext instance, you can call Getbean (Beanname) to return the bean like beanfactory. There is a significant difference between ApplicationContext initialization and Beanfactory: Beanfactory when the container is initialized, the bean is not instantiated until the first time a bean is accessed, the target bean is not instantiated , and ApplicationContext instantiates all single-instance beans when the application context is initialized. Therefore, the ApplicationContext initialization time is slightly longer than the beanfactory, but later calls do not have a "first penalty" problem.

The advantage of the

Spring 3.0 support for a class-annotation based configuration and the way in which the XML file is configured is that it is easy for the developer to control the initialization of the bean, which is more flexible than the xml-based configuration. Spring provides a dedicated ApplicationContext implementation class for the configuration based on annotation classes: Annotationconfigapplicationcontext. See an example of how to use Annotationconfigapplicationcontext to start the Spring container:
The configuration information provided by the annotated Java class: 01//① is a configuration information that provides class @Configuration   public class beans {    //② defines a Bean      @Bean ( Name =  "Car")     public car Buildcar ()          car car = new car (); Modified         car.setbrand ("Red Flag CA72");         car.setmaxspeed (200);         return car; &NBSP;&NBSP;&NBSP;&NBSP}

Boot container via configuration class with @configuration: 1//① with @configuration pojo load Bean configuration 2 ApplicationContext = new Annotationconfigapplicationcontext (Beans.class);  3 Car car = Ctx.getbean ("Car", car.class); Webapplicationcontext Introduction

Webapplicationcontext is designed specifically for Web applications, which allows initialization to be done from loading a configuration file from a path relative to the Web root directory.

A ServletContext reference can be obtained from the Webapplicationcontext, and the entire Web application context object will be placed as a property in the ServletContext so that the Web application environment can access the spring application contexts. You can get Webapplicationcontext instance from the tool class Webapplicationcontextutils provided by spring: 1 Webapplicationcontext ctx = Webapplicationcontextutils.getrequiredwebapplicationcontext (ServletContext SC); 2 Webapplicationcontext ctx = Webapplicationcontextutils.getwebapplicationcontext (ServletContext SC);

The difference between the above two tools is that the former throws an exception when a failure is obtained, and the latter returns null.

Because Web applications have more features than general applications, Webapplicationcontext extends ApplicationContext. Webapplicationcontext defines a constant root_web_application_ context_attribute that, when the context is started, The Webapplicationcontext instance is placed in the ServletContext property list with this as the key, so we can get the webapplicationcontext:1 from the Web container directly from the following statement Webapplicationcontext WAC = (webapplicationcontext) servletcontext.getattribute (webapplicationcontext.root_web_ Application_context_attribute);

Webapplicationcontext initialization

The initialization of Webapplicationcontext is different from beanfactory and ApplicationContext, because Webapplicationcontext needs ServletContext instance, This means that it must have a Web container to complete the startup work.
Spring provides the servlet and Web container listeners for starting Webapplicationcontext:
Org.springframework.web.context.ContextLoaderServlet;
Org.springframework.web.context.ContextLoaderListener.
Both of the internal implementation of the start Webapplicationcontext instance logic, we simply choose one of the two according to the specific circumstances of the Web container, and complete the configuration in Web.xml:

Booting through a web Container listener:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.