Transferred from: http://www.kokojia.com/article/12598.html
When learning a thing, if you want to understand it, it's best to think about how the framework is implemented internally, and how I would do it if I did it. I'll write an IOC di program below. Spring is the equivalent of a bean factory, you write your own bean, enter a configuration file, spring can help you automatically generate Bean object. Below we create a Java engineering SIMULATEIOC we write two beans first. The content is the same, except that the class name is different. Define a spring configuration file, we name Iocconfig.xml. Let's take a look at the Testioc.java file. Look at the results of the operation:
From this file we can see that we first created a beanfactory factory and then obtained the specified Bean object through the Getbean method. is not very magical, as long as through the different names, we can get the object we want. What the hell did beanfactory inside? This is the whole beanfactory realized. Many of them are processing XML parts, we mainly look at the above two red places.
Class bean = Class.forName (Cls.gettext ());
Object obj = bean.newinstance ();
Class.forName gets the class class of the specified class. Newinstance () Gets the object of the specified class.
Method entrypoint = Bean.getmethod (AttributeName, String.class);
Entrypoint.invoke (Obj,value);
GetMethod Gets the method invocation entry for the specified method. Then invoke invoke to execute the method.
If you want to learn more about the above four sentences. You can look at the reflection mechanism of the class file. Or read one of my other articles.
The IOC di implementations above are very simple and do not consider too many interference factors and functions. So unlike spring implementations, the principle is the same.
Go The IOC control inversion Java Reflection principle of Java Spring