Spring source parsing--start from beanfactory (i)

Source: Internet
Author: User
Tags aliases



Let 's take a look at the ABC code when we learn spring:


Beanfactory beanfactory=new classpathxmlapplicationcontext ("Applicationcontext.xml"); Usermanager usermanager= (Usermanager) Beanfactory.getbean ("Usermanagerimpl"); Usermanager.add ("DD", "D");

by adding a mapping file with a bean configuration relationship, get to our beanfactory container, and then we can get the bean in the device. Next, we'll follow these few lines of the simplest code to drill down into how spring implements the IOC container under search.



one, the core specification of the spring container


first on the source:


Public interface Beanfactory {/** * used to dereference a factorybean and distinguish it from beans * <i>created< /i> by the Factorybean. For example, if the beans named * <code>myEjb</code> is a factorybean, getting <code>&myejb</code& Gt would * return the factory, not the instance returned by the factory. */string Factory_bean_prefix = "&";/** * Return An instance, which could be shared or independent, of the given BEAN Nam E. * This method allows a Spring beanfactory to being used as a replacement for the * Singleton or Prototype design pattern. * <p>callers may retain references-returned objects in the case of Singleton beans. * <p>translates aliases back to the corresponding canonical bean name. * would ask the parent factory if the bean cannot is found in this factory instance.  * @param name The name of the bean to return * @return The instance of the bean * @throws nosuchbeandefinitionexception if There is no bean definition * withThe specified name * @throws beansexception if the bean could not be obtained */object Getbean (String name) throws Beansex ception;/** * Return An instance (possibly shared or independent) of the given bean name. * <p>behaves the same as Getbean (String), but provides a measure of type safety by * throwing a Spring beansexceptio n If the bean is not of the required type. * This means so classcastexception can ' t be thrown on casting the result correctly, * As can happen with <code>get Bean (String) </code>. * @param name The name of the bean to return * @param requiredtype type the bean must match. Can be a interface or superclass * of the actual class, or <code>null</code> for any match.  For example, if the value * is <code>object.class</code> and this method would succeed whatever the class of the * Returned instance. * @return An instance of the bean (never <code>null</code>) * @throws beannotofrequiredtypeexception if the IS An are not of The required type * @throws nosuchbeandefinitionexception if there ' no such bean definition * @throws beansexception if  The bean could not being created */object Getbean (String name, Class requiredtype) throws beansexception;/** * Does this bean Factory contain a bean definition with the given name? * <p>will Ask the parent factory if the bean cannot is found in this factory instance. * @param name The name of the bean to query * @return whether a beans with the given name is defined */boolean Containsbean (String name);/** * Is this bean a singleton? That's, would <code>getBean</code> always return the same object? * <p>will Ask the parent factory if the bean cannot is found in this factory instance. * @param name The name of the bean to query * @return are this bean a singleton * @throws nosuchbeandefinitionexception if There is no bean with the given name * @see #getBean */boolean Issingleton (String name) throws Nosuchbeandefinitionexcepti on;/** * Determine the TYpe of the Bean with the given name. * More specifically, checks the type of object <code>getBean</code> would return. * For a Factorybean, returns the type of object, the the Factorybean creates. * @param name The name of the bean to query * @return The type of the bean, or <code>null</code> if not determ inable * @throws Nosuchbeandefinitionexception If there is no bean with the given name * @since 1.1.2 * @see #getBean * @s EE factorybean#getobjecttype () */class getType (String name) throws nosuchbeandefinitionexception;/** * Return the Aliases for the given bean name, if defined. * <p>if The given name is a alias, the corresponding original bean name * and other aliases (If any) would be return Ed, with the original bean name * Being the first element in the array. * <p>will Ask the parent factory if the bean cannot is found in this factory instance. * @param name the bean name to check for aliases * @return the aliases, or an empty array if nonE */string[] getaliases (String name);} 


The above paragraph is pulled out from the spring source, in the beanfactory, the definition of the spring container of the most basic specifications, the following we will explain in turn the following methods:


1,string factory_bean_prefix = "&";


The escape definition for Factorybean, because if the object retrieved by using the bean's name is a factory-generated object, it needs to be escaped if the factory itself needs to be factorybean; For example: MYEJB is a factorybean,& MYEJB will get a factory, not a factory return instance.

about Beanfacoty and Factorybean: beanfactory is a Factory, an IOC container or Object factory,Factorybean is a Bean. In Spring , all beans are managed by Beanfactory ( also known as the IOC container ) . But for Factorybean , this bean is not a simple bean, but a factory bean that can produce or modify object generation. Its implementation is similar to the factory pattern and decorator pattern in design mode. (from:http://chenzehe.iteye.com/blog/1481476)


It can be seen that Factorybean is mainly created to simplify the assembly of complex beans.


2,object Getbean (String name) throws Beansexception;


Gets the bean instance from the IOC container, based on the Bean's name


3,object Getbean (String name, Class requiredtype) throws beansexception;



According to the Bean's name and type to obtain the bean instance, more than the previous method of type condition validation, enhanced type security authentication mechanism.



4,boolean Containsbean (String name);



find out if the container contains this bean by name


5,boolean Issingleton (String name) throws Nosuchbeandefinitionexception;


determine if the bean is a singleton.


6,class GetType (String name) throws Nosuchbeandefinitionexception;



getting the class type of the bean type may throw exceptions that do not exist for the class.



7,string[] getaliases (String name);



The bean alias is obtained, and if it is retrieved according to the alias, its original name is also retrieved.



two, from Classpathxmlapplicationcontext to Beanfactory



Beanfactory just defines the specification of the container, Spring provides a lot of implementation classes for the implementation of the container, first look at how many levels we have experienced in our code, from Classpathxmlapplicationcontext to Beanfactory:



Although Classpathxmlapplication provides several constructors, it will eventually be called:


Public Classpathxmlapplicationcontext (string[] paths, Class Clazz, ApplicationContext parent) throws Beansexception { Super (parent); Assert.notnull (Paths, "Path array must not is null");  Assert.notnull (Clazz, "Class argument must not being null"); this.configresources = new Resource[paths.length];for (int i = 0; i < paths.length; i++) {This.configresources[i] = new Classpathresource (Paths[i], clazz);} Refresh ();}



In the constructor, the main thing is to call the parent constructor, and then we look along the inheritance chain:




after the code is estimated to be added to the configuration resources, followed by the Refresh method, the real implementation of this method in Abstractapplicationcontext this abstract class:



public void Refresh () throws Beansexception, IllegalStateException {synchronized (this.startupshutdownmonitor) { This.startuptime = System.currenttimemillis (); synchronized (this.activemonitor) {this.active = true;} Tell subclass to refresh the internal bean factory.refreshbeanfactory (); Configurablelistablebeanfactory beanfactory = Getbeanfactory ();//tell the internal beans factory to use the context ' s Clas S Loader.beanFactory.setBeanClassLoader (getClassLoader ());//Populate The Bean factory with context-specific resource Editors.beanFactory.addPropertyEditorRegistrar (New Resourceeditorregistrar (this));//Configure The Bean Factory with Context Semantics.beanFactory.addBeanPostProcessor (new Applicationcontextawareprocessor (this)); Beanfactory.ignoredependencyinterface (Resourceloaderaware.class); Beanfactory.ignoredependencyinterface ( Applicationeventpublisheraware.class); Beanfactory.ignoredependencyinterface (Messagesourceaware.class); Beanfactory.ignoredependencyinterface (ApplicationcontexTaware.class);//allows post-processing of the Bean Factory in Context subclasses.postprocessbeanfactory (beanfactory); /Invoke factory processors registered with the context instance.for (Iterator it = getbeanfactorypostprocessors (). Iterato R (); It.hasnext ();) {Beanfactorypostprocessor factoryprocessor = (beanfactorypostprocessor) it.next (); Factoryprocessor.postprocessbeanfactory (beanfactory);}  if (logger.isinfoenabled ()) {if (getbeandefinitioncount () = = 0) {logger.info ("No beans defined in application context [" + GetDisplayName () + "]");} else {logger.info (Getbeandefinitioncount () + "beans defined in application context [" + getdisplayname () + "]");}} try {//Invoke factory processors registered as beans in the context.invokebeanfactorypostprocessors ();//Register Bean PR ocessors that intercept bean creation.registerbeanpostprocessors ();//Initialize message source for this Context.initmessagesource ();//Initialize Event Multicaster for this context.initapplicationeventmulticaster ();// Initialize other special beans in specific context subclasses.onrefresh ();//Check for listener beans and register THEM.R Egisterlisteners ();//Instantiate singletons this late to allow them to access the message Source.beanFactory.preInstantia Tesingletons ();//Last Step:publish corresponding event.publishevent (new contextrefreshedevent (This));} catch (Beansexception ex) {//Destroy already created singletons to avoid dangling Resources.beanFactory.destroySingleton s (); throw ex;}}}


Go to bed, tomorrow starts with the refresh ...




Spring source parsing--start from beanfactory (i)

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.