The Bean Factory of spring Exploration (top)

Source: Internet
Author: User
Tags reflection
What spring is. Spring's Chinese name is springtime, it is the spring of software developers, is a lightweight control inversion (IOC) and aspect-oriented (AOP) container framework. I use a simple example to deconstruct how spring manages Java objects.
First, define a simple pojo with the following code:
Package com.jvk.ken.spring;

public class Demo {
	private String name;

	Public demo () {
		name= "I ' m demo.";
	}

	public void Printname () {
		System.out.println (name);
	}

	public void SetName (String name) {
		this.name = name;
	}
}


The corresponding spring configuration file is as follows:

<?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:context= "http://www.springframework.org/ Schema/context "
     xsi:schemalocation="
     http://www.springframework.org/schema/context 
     http:// Www.springframework.org/schema/context/spring-context-3.1.xsd
     Http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd ">
 	<bean id=" Demo "class=" Com.jvk.ken.spring.DemoFactory "/>
</beans>



The simple test code is as follows:

Package com.jvk.ken.spring;

Import org.springframework.beans.factory.BeanFactory;
Import org.springframework.beans.factory.xml.XmlBeanFactory;
Import Org.springframework.core.io.ClassPathResource;

public class Test {public
	static void Main (string[] args) throws Exception {
		testspring ();
	}

	private static void Testspring () throws Exception {
		beanfactory bf = new Xmlbeanfactory (New Classpathresource ("Applic Ationcontext.xml "));
		Demo Bean = (demo) Bf.getbean ("demo");
		System.out.println (Bean.getclass ());
		Bean.printname ();
	}


Run the test class and output the following information, stating that a simple spring example ran successfully.

2012-3-28 22:18:07 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadbeandefinitions
Information: Loading XML Bean definitions from class path resource [Applicationcontext.xml]
class Com.jvk.ken.spring.Demo
I ' m Demo.


From a brief Java code and XML configuration file, Xmlbeanfactory assembles JavaBean by reading an XML configuration file, returning the desired object when the user invokes the Getbean method. To imitate its behavior, I define a simple beanfactory.

Package com.jvk.ken.spring;

Import Java.util.HashMap;
Import Java.util.Map;

public class Mybeanfactory {
	//save Bean's definition
	map<string, class> beans = new hashmap<string, class> (); C5/>public Object Getbean (String id) throws Instantiationexception,
			illegalaccessexception {return
		beans.get (ID). newinstance ();

	Private String xmlFile;

	Public mybeanfactory (String xmlFile) throws ClassNotFoundException {
		super ();
		This.xmlfile = XmlFile;
		Init ();
	}

	private void Init () throws ClassNotFoundException {
		//initialization and parsing XML, where the actual parsing of XML is omitted, and the hard code is used to mimic
		System.out.println ("Config file:" +xmlfile);
		String className = "Com.jvk.ken.spring.Demo";
		Class<?> loadclass = This.getclass (). getClassLoader (). LoadClass (
				className);
		Beans.put ("demo", LoadClass);
	}


The test code is as follows:

Package com.jvk.ken.spring;

public class Test {public
	static void Main (string[] args) throws Exception {
		 testnotspring ();
	}

 	private static void Testnotspring () throws Exception {
		mybeanfactory bf = new Mybeanfactory ("Applicationcontext.xml" );
		Demo Bean = (demo) Bf.getbean ("demo");
		System.out.println (Bean.getclass ());
		Bean.printname ();
	}


The following information is output after running:

Configuration file: Applicationcontext.xml
class Com.jvk.ken.spring.Demo
I ' m Demo.

The short code above shows how spring is acting as the simplest bean factory. Here's a little tweaking of the code to analyze what happens to spring. First, the method of non parametric construction of demo class is changed to private.

	Private Demo () {
		name= "I ' m demo.";
	}

Running the test code found that there was no difference in the spring test results, but my customized mybeanfactory reported the following error message:

Exception in thread ' main ' Java.lang.IllegalAccessException:Class com.jvk.ken.spring.MyBeanFactory can not access a memb Er of class Com.jvk.ken.spring.Demo with modifiers ' private ' at
	sun.reflect.Reflection.ensureMemberAccess ( reflection.java:65) at
	Java.lang.Class.newInstance0 (class.java:349) at
	java.lang.Class.newInstance ( class.java:308) at
	Com.jvk.ken.spring.MyBeanFactory.getBean (mybeanfactory.java:12)
	at Com.jvk.ken.spring.Test.testNotSpring (test.java:25) at
	Com.jvk.ken.spring.Test.main (test.java:9)


Spring is so magical. Not also, I wrote the code is too simple, slightly modified, can also be directly run.

Public Object Getbean (String id) throws Exception {
		Class class1 = beans.get (id);
		Constructor declaredconstructor = Class1.getdeclaredconstructor ();
		Declaredconstructor.setaccessible (true);
		return declaredconstructor.newinstance ();
	}


These are the purest javabean of spring container management. Spring also supports a different kind of bean, called a factory bean, example wins, see Code

Package com.jvk.ken.spring;

Import Org.springframework.beans.factory.FactoryBean;

public class Demofactory implements Factorybean {

	@Override public
	Object GetObject () throws Exception {
		return new Demo ();
	}

	@Override public
	Class Getobjecttype () {return
		demo.class;
	}

	@Override Public
	Boolean Issingleton () {return
		false;
	}

}


After adding the Demofactory class, modify the spring configuration file at the same time

<bean id= "Demo" class= "Com.jvk.ken.spring.DemoFactory"/>

Other code does not make changes, after running the test code, the output is exactly the same as the original. Why is clearly configured with the ID of the demo class for Com.jvk.ken.spring.DemoFactory, the return result is a demo instance, because spring detects that demofactory is a special bean that implements the Factorybean interface, returns The GetObject method is invoked before the result, so the demo object is finally obtained. Of course, if we really need to get a factory bean, we can write Bf.getbean ("&demo") like this.

At this point, we've solved spring's normal bean and factory bean from the most fundamental principle, for the previous one. The following is an introduction to the Bean's property injection (that is, when the bean is instantiated, and its set method settings are called), and how spring is constructing the bean from the annotation after parsing the XML configuration and using annotations.


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.