Understand Spring's bean factory

Source: Internet
Author: User

a referring to the factory, let's recall the factory method and the abstract factory model we learned earlier:


Work Factory method : For Product dimension, can produce new product, also can produce new product factory, can expand product dimension. But if we want to produce a product line in an ordinary factory, it will be particularly troublesome .if the resultingAppleyou have to produceapplefactory, if the resultingMushroom, you have to producemushroomfactory.This will be a factory flood.


Abstract Factory: for the product line, you can expand on a range of products. The disadvantage is that if a new product is produced, there will be a lot of changes.  

Spring Factory: can be expanded in the product line, but also to determine the product variety. Here's an example of spring:


1. First define an interface of two classes:

public class car implements moveable {public void run () {System.out.println ("O (∩_∩) o haha ~, open convertible car Home ~~~~~");}

public class Train implements moveable {@Overridepublic void run () {System.out.println ("Woo-hoo ~ ~, can only squeeze train ~ ~ ~");}
public interface Moveable {void run ();

2. Add a jar package that references spring to add an XML file : Applicationcontext.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans><bean id= "V" class= "Com.tgbstd.spring.factory.Car" > </bean></beans>


3. Test class:

public static void Main (string[] args) throws Exception {beanfactory f = new Classpathxmlapplicationcontext ("Applicationc Ontext.xml "), Object o =f.getbean (" V ");  Incoming idmoveable m = (moveable) o; M.run ();}}

Spring uses itself to read the XML configuration file and implements the Beanfactory interface. We only need to pass in the configuration file name on the client, the ID of the incoming profile, we can find the corresponding class-generated object based on the ID, and return the object as a bean.

The above is a well-packaged spring, so how do we simulate spring's principle?

Spring Simulation: define a beanfactory, which has its own implementation, the most common implementation of Classpathxml, read from here XML, put the information you read in a MAP and take it out when you want it.


A. Defining Beanfactory interfaces and Getbean methods

Public interface Beanfactory {Object Getbean (String ID);}


B. Define your own implementation : Create a read XML file class, Classpathxmlapplicationcontext. The previous article has introduced how to read the XML file, here will not repeat, see the example directly.
public class Classpathxmlapplicationcontext implements Beanfactory {//the contents of all the configuration files are read out and stored in the Map private map<string, object> container = new hashmap<string,object> ();//define Constructor public Classpathxmlapplicationcontext (String FileName) throws Exception {Saxbuilder sb = new Saxbuilder ();D ocument doc = Sb.build (This.getclass (). getClassLoader ().   getResourceAsStream (FileName)); Get the config file element root = Doc.getrootelement ();   List List = Xpath.selectnodes (Root, "/beans/bean"); Loop traversal node for (int i = 0; i < list.size (); i++) {Element bean = (Element) list.get (i); String id = bean.getattributevalue ("id"); String clazz = Bean.getattributevalue ("class"), Object o =class.forname (clazz). newinstance (); Container.put (ID, O); Store object//related process output System.out.println ("id=" + ID); System.out.println ("Get specific class information by ID:" + "class");}} @Override//Call Getbean to return the received information to the client public Object Getbean (String ID) {return container.get (ID);}}

In the construction method of the Classpathxmlapplicationcontext class, there is a file name that, through filename, points to the configuration file and is able to read the information from the configuration file. And all the information that is read from the configuration file is stored in the map container.
C. Test class

public class Test {public static void main (string[] args) throws Exception {//Parent class reference to child class object, find configuration file beanfactory f = new Classpa Thxmlapplicationcontext ("Com/tgbstd/spring/factory/applicationcontext.xml");//incoming Idobject o = F.getBean ("V"); Moveable M = (moveable) o; M.run ();   }}

D. Results:

The above is a simple introduction to the principle of spring's creation of the Bean factory. In fact, the bean mainly through its own definition of a beanfactory factory implementation, through the constructor to pass in the initial value, read the XML configuration file information. And the read ID as the key value, the object to read as the value, stored in the map container. When the client needs to obtain, as long as the incoming ID, can be read out of the device.    

Baidu Encyclopedia definition:Spring is a lightweight control inversion (IOC) and facet-oriented (AOP) container framework. The concept of the Bean Factory is that spring acts as an IOC ( interface-oriented or abstract-oriented programming, writing specific things in a configuration file.) When we need to change, we just need to modify the configuration file, for example, to change car to train. The result we get is the way to do the train home. ) The base of the container. It is conceivable that the principle of understanding bean factory is very necessary.

Understand Spring's bean factory

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.