The Bean Factory of spring Exploration (next)

Source: Internet
Author: User

The previous section briefly demonstrates the management of the bean under Spring using XML configuration, which uses annotations directly in Java code without XML configuration, and how spring manages beans. First add @component annotation to the head of demo class, the code is as follows:

Import org.springframework.stereotype.Component;

@Component (value= "demo") Public
class Demo {
//Here omit some code
}


Second, modify the original XML configuration "<bean id=" demo "class=" Com.jvk.ken.spring.Demo "/>" as "<context:component-scan base-package=" Com.jvk.ken.spring "/>", the other parts do not make changes, run test code, we know that the two configuration form to achieve the same effect. How did spring manage the JavaBean through annotations? Here's a simple class to simulate spring's factory class with the following code:

Package com.jvk.ken.spring;
Import Java.io.File;
Import Java.io.FileFilter;
Import java.lang.annotation.Annotation;
Import Java.lang.reflect.Constructor;
Import Java.net.URL;
Import Java.net.URLDecoder;
Import java.util.Enumeration;
Import Java.util.HashMap;

Import Java.util.Map;

Import org.springframework.stereotype.Component;

	public class Mybeanfactory {//Save Bean's definition map<string, class> beans = new hashmap<string, class> ();
		Public Object Getbean (String id) throws Exception {Class Class1 = beans.get (ID);
		Constructor declaredconstructor = Class1.getdeclaredconstructor ();
		Declaredconstructor.setaccessible (TRUE);
	return Declaredconstructor.newinstance ();

	Private String XmlFile;
		Public mybeanfactory (String xmlFile) throws Exception {super ();
		This.xmlfile = XmlFile;
	Init ();
		} private void Init () throws Exception {//initialization and parsing XML, where the actual parsing of XML is omitted, and the hard code mimics the System.out.println ("Config file:" + xmlFile);
		String basepkg = "com.jvk.ken.spring"; System.out.pRintln ("According to configuration, description of the note package is" + basepkg); enumeration<url> resources = Thread.CurrentThread (). Getcontextclassloader (). Getresources (BasePkg.replace ('
		.', '/'));
			while (Resources.hasmoreelements ()) {URL url = resources.nextelement ();
			String protocol = Url.getprotocol (); If it is saved as a file on the server, the jar package or other forms of reference are not considered as if ("File". Equals (protocol)) {//Get the package's physical path String FilePath = URLDECODER.D
				Ecode (Url.getfile (), "UTF-8");  Gets all the class files under the package, regardless of the directory recursive lookup file[] classfiles = new file (FilePath). Listfiles (New FileFilter () {public
							Boolean Accept (file file) {return File.getname (). EndsWith (". Class");

				}
						});
					for (File f:classfiles) {String filename = f.getname ();
					String className = filename.substring (0, Filename.length ()-6);
					Class<?> loadclass = This.getclass (). getClassLoader (). LoadClass (basepkg + '. ' + className);
					annotation[] annotations = loadclass.getannotations (); for (Annotation a:annotations) {if (a instanceof Component) {String Beanid = ((Component) a). Value ();
							Beans.put (Beanid, loadclass);
						Break
 }
					}

				}

			}
		}

	}
}


Run the following test code to see that Mybeanfactory does achieve a similar effect in spring.

mybeanfactory bf = new Mybeanfactory ("Applicationcontext.xml");
		Demo Bean = (demo) Bf.getbean ("demo");
		System.out.println (Bean.getclass ());
		Bean.printname ();


So far, the rationale behind spring's creation of beans for us has been demonstrated. But spring can do much more than the demo, such as injecting the initial value through the constructor method, injecting the literal or other bean instances through the setter method, and adding a method for the bean's method of blocking, the post blocking method and the exception blocking method, and so on. How do these magical features spring do it? The next article will analyze these and specifically deconstruct the secrets of spring's declarative transactions.

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.