Java control inversion and dependency injection

Source: Internet
Author: User
Tags gettext

1. Introduction

Dependency injection and control inversion are intended to enable the decoupling of classes from classes, to improve the scalability and maintainability of the system, and to introduce this concept through an example.

2. Case studies

1) class coupling under normal conditions

Main.java

 Public classMain { Public Static voidMain (string[] args) {/******** general notation, strong coupling between the main class and the Chinese class and the American class ***********/          //Chinese and American, when classes and methods are modified, the classes and methods here also need to be modifiedChinese Chinese =NewChinese (); Chinese.sayhelloworld ("Zhang San"); American American=NewAmerican (); American.sayhelloworld ("Jack"); }}/******************** General Method ***************************/InterfaceHuman { Public voidSayHelloWorld (String name);}classChineseImplementsHuman { Public voidSayHelloWorld (string name) {string HelloWorld= "Hello," +name;     System.out.println (HelloWorld); }}classAmericanImplementsHuman { Public voidSayHelloWorld (string name) {string HelloWorld= "Hello," +name;     System.out.println (HelloWorld); }}

As can be seen from the above code: there is a strong coupling between the main class and the Chinese class and the American class, and when Chinese and American classes and methods are modified, the classes and methods here also need to be modified. Not easy to extend and maintain.

2) Factory method to decouple

 Public classMain { Public Static voidMain (string[] args) {/******** factory method, the main class and class Chinese and American are no longer coupled, only and their interface human coupling ***********/          //Modifications also need to be modified in the main class to modify these strings//Chinese and American, when classes and methods are modified, only methods need to be modifiedHumanfactory humanfactory =Newhumanfactory (); Human Human1= Humanfactory.gethuman ("Chinese"); Human1.sayhelloworld ("Zhang San"); Human human2= Humanfactory.gethuman ("American"); Human2.sayhelloworld ("Jack"); }}/******************** Factory Method ***************************/InterfaceHuman { Public voidSayHelloWorld (String name);}classHumanfactory { PublicHuman Gethuman (String type) {if("Chinese". Equals (Type) {               return NewChinese (); } Else {               return NewAmerican (); }     }}


As can be seen from the above code: the main class and the class Chinese and American are no longer coupled, only and its interface human coupling, modified also need to modify the main class to modify these strings, when the class and method modification, only the method needs to be modified. This reduces the coupling of main class and Chinese, American class to some extent

3) Dependency Injection and control inversion

 Public classMain { Public Static voidMain (string[] args) {/******************** IOC control inversion and dependency injection ***************************/          //using a container to inject attribute values directly through an XML file, add only the required//Chinese and American, when classes and methods are modified, the code does not have to be modified at all, only the XML file needs to be modified to fully realize the decouplingBeanfactory beanfactory =Newbeanfactory (); Beanfactory.init ("/config.xml"); UserBean UserBean= (UserBean) beanfactory.getbean ("UserBean"); System.out.println ("Username=" +userbean.getusername ()); System.out.println ("Password=" +Userbean.getpassword ()); }}/******************** IOC control inversion and dependency injection ***************************///Here's the spring IOC implementation: The Bean factoryclassBeanfactory {Privatemap<string, object> beanmap =NewHashmap<string, object>();  Public voidInit (String fileName) {Try {               //reads the specified configuration fileSaxreader reader =NewSaxreader (); //System.out.println (xmlpath);String realpathstring =NewFile (""). Getcanonicalpath (); Document Document= Reader.read (NewFile (realpathstring + "/src/com/devin/") +fileName); Element Root=document.getrootelement ();               Element foo; //traversing Beans                for(Iterator i = root.elementiterator ("Bean"); I.hasnext ();) {Foo=(Element) i.next (); //gets the Bean's property ID and ClassAttribute id = foo.attribute ("id"); Attribute CLS= Foo.attribute ("Class"); //Use the Java reflection mechanism to get the class object through the name of ClassClass Bean =Class.forName (Cls.gettext ()); //get information for the corresponding classJava.beans.BeanInfo info =Java.beans.Introspector.getBeanInfo (Bean); //gets its property descriptionJava.beans.PropertyDescriptor pd[] =info.getpropertydescriptors (); //ways to set valuesMethod MSet =NULL; //Create an ObjectObject obj =bean.newinstance (); //iterate over the property properties of the Bean                     for(Iterator ite = Foo.elementiterator ("property")); Ite.hasnext ();) {Element Foo2=(Element) ite.next (); //gets the property's name attributeAttribute name = Foo2.attribute ("name"); String value=NULL; //gets the value of the property's child element, value                          for(Iterator ite1 = Foo2.elementiterator ("value")); Ite1.hasnext ();) {Element node=(Element) ite1.next (); Value=Node.gettext ();  Break; }                          for(intk = 0; K < Pd.length; k++) {                              if(Pd[k].getname (). Equalsignorecase (Name.gettext ())) {MSet=Pd[k].getwritemethod ();                              Mset.invoke (obj, value); }                         }                    }                    //put the object in Beanmap, where key is the ID value and value is the objectBeanmap.put (Id.gettext (), obj); }          } Catch(Exception e) {System.out.println (e.tostring ()); }     }     //gets the bean's object through the bean's ID.      PublicObject Getbean (String beanname) {Object obj=Beanmap.get (beanname); returnobj; }}userbean.java Public classUserBean {PrivateString UserName; PrivateString password;  PublicString GetPassword () {returnpassword; }      PublicString GetUserName () {returnUserName; }      Public voidsetusername (String userName) { This. UserName =UserName; }      Public voidSetPassword (String password) { This. Password =password; }}config.xml<?xml version= "1.0" encoding= "UTF-8"?><beans> <bean id= "UserBean"class= "Com.devin.UserBean" > <property name= "userName" > <value> Zhang San </value> & lt;/property> <property name= "password" > <value>Jack</value> </pro Perty> </bean></beans>

Description: Simulating the implementation of the IOC in spring, although only a small part of the process of dependency injection in spring is done, it is a good illustration of the application of the Java Reflection mechanism in spring, enabling us to better understand the implementation of the IOC in principle.

Java control inversion and dependency injection

Related Article

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.