Self-taught IOC

Source: Internet
Author: User
Tags scream

How can I avoid pulling IOC if I have been covered for so many times? However, if I do this, it may be more interesting. Here is my self-taught IOC route.

I: first, the whole IOC: I remember that the most famous container of IOC is spring, and the form is to create classes using configuration files... the general route is XML-> map-> bean. If you know this, you can first
1. Bean: The IOC container stores beans. I 'd better have a bean with fewer attributes. This is not too embarrassing.

package bean;public class Student {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    }
View code

2. xml: I know what XML is,...
Nothing, du Niang, is roughly like this, so that my IOC container can look like this

<? XML version = "1.0" encoding = "UTF-8"?> <IOC> <bean id = "English" class = "bean. student "> <Name> Li Lei </Name> </bean> <bean id =" Chinese "class =" bean. student "> <Name> Han Meimei </Name> </bean> </IOC>
View code

3. XML-> map: Read the configuration file to map/memory.
1. I need to know how to find the path. I forgot a bit. For more information, see How to get the file.
2. for XML operations, I know there is a dom4j, but I have never used it, but I have APIs

package ioc;import java.io.File;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.apache.commons.beanutils.BeanUtils;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;@SuppressWarnings({"unchecked","rawtypes"})public class Init {        private static Map<String, Object> ioc = new HashMap<String, Object>();    public static Object getBean(String key){        return ioc.get(key);    }        public Init(){        try {            readXml("src/ioc.xml");        } catch (Exception e) {            e.printStackTrace();        }    }        public static void readXml(String file) throws Exception {        Document doc = load(file);        Element root = doc.getRootElement();        for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {            Element e = (Element) iterator.next();            String _id = e.attributeValue("id");            String _class = e.attributeValue("class");                        List<Element> list = e.elements();            Map<String, String> map = new HashMap<String, String>();            for (Element _e : list) {                map.put(_e.getName(), _e.getText());            }                   Object obj=Class.forName(_class).newInstance();            BeanUtils.populate(obj, map);            ioc.put(_id, obj);        }    }    public static Document load(String filename) {        Document document = null;        try {            document = new SAXReader().read(new File(filename));        } catch (Exception ex) {            ex.printStackTrace();        }        return document;    }}
View code

4. Test

Public static void main (string [] ARGs) {New Init (); student English = (student) Init. getbean ("English"); Student Chinese = (student) Init. getbean ("Chinese"); system. out. println ("I am an English class representative:" + English. getname (); system. out. println ("I am a Chinese class representative:" + Chinese. getname ());}

Thinking: He/IOC suddenly gave me the feeling of a variable. If there is no variable, even a local variable, it will become messy and disgusting, when variables solve this problem (they say this is coupling), isn't IOC a dedicated way to provide variable classes (variable classes) throughout the program? In this case, if you need to write the function or meaning of IOC, you can copy the variable (the article on the function and meaning ).
Conclusion: IOC provides variable classes for the entire program.

Ii. Du Niang IOC's understanding: Just like seeing the new world, I can't wait for a Niang.

Du Niang explained, Wikipedia explanation: these explanations are like a fairy fight, so they will join in a lively, personal field, Dangdang cannon fodder... however, I have noticed the design pattern and the implementation method of dependency injection, which reminds me of the first gof pattern.

Explanation by my girlfriend, gear: a very vivid explanation

Iii. Policy mode and IOC container usage: Remember to use the first gof mode that I just thought of and use it decisively --> here Spring is used, and my IOC does not support ref --!

Modify the test case of the Policy mode. XML is:

<Bean id = "flynoway" class = "gof. fly. flynoway "> </bean> <bean id =" flyrocketpowered "class =" gof. fly. flyrocketpowered "> </bean> <bean id =" flywithwings "class =" gof. fly. flywithwings "> </bean> <bean id =" mutequack "class =" gof. quack. mutequack "> </bean> <bean id =" quack "class =" gof. quack. quack "> </bean> <bean id =" Squeak "class =" gof. quack. squeak "> </bean> <bean id =" green fur Duck "class =" gof. duck "> <property name =" name "value =" "> </property> <property name =" flybehavior "ref =" flywithwings "> </property> <Property name = "quackbehavior" ref = "quack"> </property> </bean> <bean id = "Braised Duck" class = "gof. duck "> <property name =" name "value =" duck with red-headed underpants "> </property> <property name =" flybehavior "ref =" flyrocketpowered "> </property> <property name = "quackbehavior" ref = "Squeak"> </property> </bean> <bean id = "Model Duck" class = "gof. duck "> <property name =" name "value =" Model Duck "> </property> <property name =" flybehavior "ref =" flynoway "> </property> <Property name = "quackbehavior" ref = "mutequack"> </property> </bean>
View code

Test:

Classpathxmlapplicationcontext CTX = new classpathxmlapplicationcontext ("applicationcontext. XML "); (duck) CTX. getbean ("green-haired Duck ")). display (); (duck) CTX. getbean ("Braised Duck ")). display (); (duck) CTX. getbean ("Model Duck ")). display ();
View code

As for the results, you know:

Look, the duck green-haired duck is flying with wings to scream and see, the duck red-headed underwear is wearing a duck and riding a rocket to scream and scream, the duck model duck will not fly and will not scream
View code

Conclusion: If IOC is a mode, it must be a policy mode + factory mode, or a factory mode with initialization (configurable). Of course, if you want to interview, never learn from me. If you want to talk about it, it's just a runny nose...
4. I need an IOC that can run on the Web: I have learned about the IOC mode, but I hope my IOC can run under the WEB Project, and initialize the program on the web, not too simple

Create a servlet to initialize IOC and specify the IOC to load at runtime.

  <servlet-mapping>    <servlet-name>InitServlet</servlet-name>    <url-pattern>/servlet/InitServlet</url-pattern>  </servlet-mapping>      <servlet>    <servlet-name>InitServlet</servlet-name>    <servlet-class>ioc.InitServlet</servlet-class>        <load-on-startup>1</load-on-startup>  </servlet>
View code

Thinking: There are four ways to run web. xml. Can I start it in four ways?
V. What is the difference between IOC and spring? Just because we don't duplicate the wheel?
XML: I have read the configuration file of spring and it is different from mine. At first, I thought it was no big deal and I understood it differently. But when I saw the DTD, I understood it in seconds.
Web. xml: There are several startup Methods
Other related functions: You can see the jar package. It provides more functions.

6. Photo and tiger
Spring provides a lot of simple methods. Doesn't uncle write it by himself? After the words are written, they don't feel so big. What are the matches in their source code...

7. Conclusion

Go back

8. Comparison of large IOC (I can find the IOC framework to prove that I have used many IOC frameworks, but spring is worthy of spring)
Guice: a lightweight IOC container developed by Google
Picocontainer: it uses the inversion of control mode and template method mode to provide component-oriented development and Running Environments (I like micro)
Jdon: Made in China
............
Summary After comparison: 1. There are more and more similar frameworks, fewer and fewer code, and faster speed. It seems that you have to re-understand and do not repeat the wheel ..
2. I am deeply aware that this malicious society... the IOC of JavaScript is gross.
8: source code (spring is too cool B, let's look at the tiny ones first)
It's time for girls to understand the source code, focusing on concepts, design/encapsulation methods, and other features.

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.