The Beanfactory and ApplicationContext of Spring Series

Source: Internet
Author: User

First, Beanfactory
Beanfactory is the "heart" of Spring. It is the true face of the Spring IoC container. Spring uses Beanfactory to instantiate, configure, and manage beans.

Beanfactory: Is the core interface of the IOC container, which defines the basic functions of the IOC, and we see that it mainly defines the Getbean method. The Getbean method is a starting point for the IOC container to get the bean object and raise the dependency injection. The function of a method is to return a bean of a particular name.

Beanfactory are "hard-working people" that initialize beans and invoke their life-cycle methods. Note that beanfactory can only manage the life cycle of a singleton (Singleton) Bean. It cannot manage the life cycle of prototypes (prototype, non-singleton) beans. This is because the prototype Bean instance is passed to the client after it is created, and the container loses its reference to it.

Beanfactory has a huge inheritance, implementation system, there are many sub-interfaces, implementation classes. Take a look at the basic class architecture of Beanfactory (interface-based):

This is my Beanfactory basic class architecture, which does not include a strong applicationcontext system.
Specific:
1, beanfactory as a main interface does not inherit any interface, is called a first- level interface .
2, there are 3 sub-interfaces inherited it, to enhance the function. These 3 sub-interfaces are called two-level interfaces .
3, configurablebeanfactory can be called three-level interface , the two-level interface hierarchicalbeanfactory has been enhanced again, It also inherits another external interface Singletonbeanregistry
4, Configurablelistablebeanfactory is a more powerful interface, inherited all the above interface, all-encompassing, called the Four-level interface .
(This 4-level interface is the basic interface system for beanfactory.) To continue, here are the 2 abstract classes and 2 implementation classes of the inheritance relationship:)
5, Abstractbeanfactory as an abstract class, the implementation of the three-level interface Configurablebeanfactory most functions.
6, Abstractautowirecapablebeanfactory is also an abstract class, inherited from Abstractbeanfactory, and additional implementation of the two-level interface autowirecapablebeanfactory
7, Defaultlistablebeanfactory inherits from the Abstractautowirecapablebeanfactory, realizes the most powerful four level interface Configurablelistablebeanfactory, and implements a foreign interface beandefinitionregistry, it is not an abstract class.
8, the last is the most powerful xmlbeanfactory, inherit from defaultlistablebeanfactory, rewrite some functions, make oneself more powerful.

Summarize:
Beanfactory's class architecture seems to be confusing, and it's really easy to understand from top to bottom.

Let's take a look at the source code of Beanfactory:

Package Org.springframework.beans.factory;public interface Beanfactory {/** * is used to refer to an instance, or to separate it from the bean generated by the factory, i.e. if a FA    Ctorybean's name is a, then &a will get that FACTORY */String Factory_bean_prefix = "&";    /* * Four different forms of Getbean method, get instance */Object Getbean (String name) throws Beansexception;    <T> T Getbean (String name, Class<t> requiredtype) throws beansexception;    <T> T Getbean (class<t> requiredtype) throws beansexception;    Object Getbean (String name, Object ... args) throws beansexception; Boolean Containsbean (String name); Whether there is a Boolean Issingleton (string name) throws nosuchbeandefinitionexception;//is a single-instance Boolean Isprototype (string n            AME) throws nosuchbeandefinitionexception;//is a prototype (multi-instance) Boolean Istypematch (String name, class<?> targetType) Throws nosuchbeandefinitionexception;//name, type matches class<?> getType (String name) throws Nosuchbeandefiniti Onexception; Get type string[] getaliases (String name);//RootGets the alias of the instance according to the name of the instance} 

Specific:
1, 4 methods to get an instance. The overloaded method of the Getbean.
2, 4 methods of judgment. Determines whether there is a singleton, a prototype, or a name type that matches.
3, a method to get the type, a method to get the alias. Gets the type by name, gets the alias by name. Glance!
Summarize:
Of these 10 methods, it is clear that this is a typical factory interface for plant mode.

The most common implementation class for Beanfactory is Xmlbeanfactory, which can obtain resources from classpath or file systems.

(1) file File = new file ("Filesystemconfig.xml"); Resource Resource = new Filesystemresource (file); Beanfactory beanfactory = new Xmlbeanfactory (Resource);
(2) Resource Resource = new Classpathresource ("Classpath.xml"); Beanfactory beanfactory = new Xmlbeanfactory (Resource);

Xmlbeanfactory can load the XML configuration file. Suppose we have a car class:

 package Spring.ioc.demo1;public class Car {private String brand;    private String color;    private int maxspeed;    Public String Getbrand () {return brand;    } public void Setbrand (String brand) {This.brand = brand;    } public String GetColor () {return color;    The public void SetColor (String color) {this.color = color;    } public int Getmaxspeed () {return maxspeed;    } public void Setmaxspeed (int maxspeed) {this.maxspeed = Maxspeed; The public String toString () {return ' The car is: ' + getbrand () + ', color is: ' +getcolor () + ', Maxspeed is: "+g    Etmaxspeed ();        Public car () {} public car (string brand, string color, int maxspeed) {this.brand = brand;        This.color = color;    This.maxspeed = Maxspeed;                } public void introduce () {System.out.println ("Brand:" + brand + "; color:" + color + "; Maxspeed:"    + maxspeed); }}

We do this by configuring in Applicationcontext.xml:

<bean id= "car1" class= "Spring.ioc.demo1.Car"        p:brand= "Spring injection-red flag 001"         p:color= "Spring injection-Purple"         p: maxspeed= "520"/>

To start the spring IOC container with Xmlbeanfactory implementation:

public static void Main (string[] args) {    Resourcepatternresolver resolver = new Pathmatchingresourcepatternresolver ();      Resource res = Resolver.getresource ("Classpath:applicationContext.xml");      
ApplicationContext factory=new classpathxmlapplicationcontext ("Applicationcontext.xml"); Car car = Factory.getbean ("Car1", car.class); System.out.println ("Car object has been initialized"); System.out.println (Car.getmaxspeed ());}

1. The xmlbeanfactory uses resource to load the spring configuration information ice to launch the IOC container, and can then get the beans from the IOC container via Factory.getbean.
2. When launching an IOC container through beanfactory, the bean defined in the configuration file is not initialized, and the initialization action occurs at the first call.
3. For a single-instance (singleton) bean, beanfactory caches the bean instance, so the second time the Getbean is used, the bean is fetched directly from the IOC container cache.

Second, ApplicationContext

If Beanfactory is the heart of spring, then ApplicationContext is the complete body, ApplicationContext derived from beanfactory, providing more practical application-oriented functionality. In Beanfactory, many functions need to be implemented programmatically, while in ApplicationContext they can be implemented by configuration.

The Beanfactorty interface provides a configuration framework and basic functionality, but does not support spring's AOP features and Web applications. The ApplicationContext interface, as a derivation of the beanfactory, provides all beanfactory functionality. And the ApplicationContext is also extended functionally, with the following features compared to Beanfactorty,applicationcontext:

(1) Messagesource, providing international message access
(2) resource access, such as URLs and files
(3) Event propagation characteristics, i.e. support for AOP features
(4) Loading multiple (inherited relationships) contexts so that each context is focused on a specific level, such as the web layer of the application

ApplicationContext: is another important interface of the IOC container, which inherits the basic functions of beanfactory, and also inherits the advanced functions of the container, such as: Messagesource (internationalized Resource interface), Resourceloader (Resource Loading interface), Applicationeventpublisher (Application Event Publishing interface), and so on.

Three or two differences

1.BeanFactroy uses lazy loading as a way to inject beans, which is to instantiate a bean only when it is used (called Getbean ()), so that we cannot discover some of the existing spring configuration problems. ApplicationContext, on the other hand, creates all the beans at once when the container is started. This way, when the container starts, we can discover the configuration errors that exist in spring. The only disadvantage relative to the basic beanfactory,applicationcontext is the memory footprint. When the application configuration bean is large, the program starts slowly.

Beanfacotry lazy Loading, if one of the bean's properties is not injected, beanfacotry is loaded until the first time the Getbean method is used to throw an exception, and ApplicationContext is initialized itself as a test, This helps to check if the dependency property is injected, so we typically choose to use ApplicationContext.
The application context pre-loads all the singleton beans after the context is started. By preloading a single instance bean, make sure you don't have to wait when you need it, because they're already created.

2.BeanFactory and ApplicationContext both support the use of beanpostprocessor, beanfactorypostprocessor, but the difference between the two is: Beanfactory need to manually register, The ApplicationContext is automatically registered. (ApplicationContext has added some better-used features than beanfactory.) And many functions of beanfactory need to be implemented programmatically and ApplicationContext can be implemented by configuration. such as post-processing beans, ApplicationContext directly configured in the configuration file can be beanfactory this to be displayed in the code to be written out to be recognized by the container. )

3.beanFactory is primarily faced with the spring framework infrastructure, facing spring itself. The Applicationcontex is mainly used by developers with spring. The basic use of Applicationcontex is not beanfactory.

Iv. Summary

Role:
1. The beanfactory is responsible for reading the bean configuration document, managing the bean's loading, instantiating, maintaining the dependency between the beans, and responsible for the bean's declaration cycle.

2. ApplicationContext provides more complete framework functionality in addition to the functionality provided by the beanfactory above:
A. Internationalization support
B. Resource access: Resource rs = ctx. GetResource ("Classpath:config.properties"), "File:c:/config.properties"
C. Event delivery: By implementing the Applicationcontextaware interface

3. Commonly used to get ApplicationContext

Filesystemxmlapplicationcontext: Created from the file system or URL specified by the XML configuration file, the parameter is a configuration file name or an array of file names, with a relative path and an absolute path.

ApplicationContext factory=new filesystemxmlapplicationcontext ("Src/applicationcontext.xml"); ApplicationContext factory=new filesystemxmlapplicationcontext ("E:/workspaces/myeclipse 8.5/Hello/src/ Applicationcontext.xml ");

Classpathxmlapplicationcontext: Created from the classpath XML configuration file, you can read the configuration file from the jar package. There are three ways to classpathxmlapplicationcontext a compiled path:

ApplicationContext factory = new Classpathxmlapplicationcontext ("Classpath:applicationContext.xml"); ApplicationContext factory = new Classpathxmlapplicationcontext ("Applicationcontext.xml"); ApplicationContext factory = new Classpathxmlapplicationcontext ("File:e:/workspaces/myeclipse 8.5/Hello/src/ Applicationcontext.xml ");

Xmlwebapplicationcontext: Reading a configuration file from the Web application's root directory requires a configuration in XML. config, which can be configured with a listener or servlet to implement

<listener><listener-class>org.springframework.web.context.contextloaderlistener</listener-class ></listener>

Or

<servlet><servlet-name>context</servlet-name><servlet-class> org.springframework.web.context.contextloaderservlet</servlet-class><load-on-startup>1</ Load-on-startup></servlet>

Either way, the default profile is Web-inf/applicationcontext.xml, or you can use Context-param to specify the configuration file

<context-param><param-name>contextconfiglocation</param-name><param-value>/web-inf/ Myapplicationcontext.xml</param-value></context-param>

The Beanfactory and ApplicationContext of Spring Series

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.