Control inversion and dependency injection of Java

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

PublicClassMain {PublicStaticvoidMain (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 modified Chinese Chinese =NewChinese (); Chinese.sayhelloworld ("Zhang San"); American American =NewAmerican (); American.sayhelloworld ("Jack"); }}/**General Method ***************************/InterfaceHuman {public void SayHelloWorld (String name); class Chinese implements Human { public void SayHelloWorld (string name) {string helloWorld = "Hello, "+ name; System.out.println (HelloWorld); }}class American implements Human { public void SayHelloWorld (string name) {string Hellowo Rld = "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

PublicClassMain {PublicStaticvoidMain (string[] args) {/**The factory method, the main class and the class Chinese and American are no longer coupled, only with 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 modified humanfactory humanfactory =NewHumanfactory (); Human human1 = Humanfactory.gethuman ("Chinese"); Human1.sayhelloworld ("Zhang San"); Human human2 = Humanfactory.gethuman ("American"); Human2.sayhelloworld ("Jack");}}/**Factory Method *************************** /interface Human {public  void sayhelloworld (String name);} class Humanfactory { public Human Gethuman (String type) { if ("Chinese". Equals (Type)) { re Turn new Chinese ();} else { return new American ();          }}} 

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

PublicClassMain {PublicStaticvoidMain (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 need to modify the XML file, fully realize the understanding of the decoupling beanfactory 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 {Private map<string, object> Beanmap =New Hashmap<string, object>();PublicvoidInit (String fileName) {Try{//Reads the specified configuration file Saxreader reader =NewSaxreader ();//System.out.println (Xmlpath); String realpathstring =New File (""). Getcanonicalpath (); Document document = Reader.read (New File (realpathstring + "/src/com/devin/") +FileName); Element root =Document.getrootelement (); Element foo;//Traversing beansfor (Iterator i = root.elementiterator ("Bean"); I.hasnext ();) {foo =(Element) I.next ();//Gets the Bean's property ID and class Attribute id = foo.attribute ("id"); Attribute cls = Foo.attribute ("Class");//Use the Java reflection mechanism to get the class object class bean with the class name =Class.forName (Cls.gettext ());//Get information about class Java.beans.BeanInfo info =Java.beans.Introspector.getBeanInfo (Bean);//Gets its property description java.beans.PropertyDescriptor pd[] =Info.getpropertydescriptors ();//Methods for setting values method MSet =Null;//Create an Object obj =Bean.newinstance ();//Iterate over the property properties of the Beanfor (Iterator ite = Foo.elementiterator (the "property"); Ite.hasnext ();) {Element Foo2 =(Element) Ite.next ();//Gets the name attribute of the property Attribute name = Foo2.attribute ("name"); String value =Null;//Gets the value of the property's child element, valuefor (Iterator ite1 = Foo2.elementiterator ("Value"); Ite1.hasnext ();) {Element node =(Element) Ite1.next (); Value =Node.gettext ();Break; }for (int k = 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.javaPublicClassUserBean {PrivateString UserName;PrivateString password;PublicString GetPassword () {ReturnPassword }PublicString GetUserName () {return UserName;} public void setusername (String userName) { this.username = userName;} public void SetPassword (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> </property> < Property name= "Password" > <value>Jack</value> </property> </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.

Control inversion and dependency injection of Java

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.