코딩 분석 Spring 의존 주입 의 원리

17230 단어 spring

1. 의존 대상 주입
기본 형식 개체 주입:
<bean id=”orderService” class=”com.wxy.service.OrderServiceBean”>

   <constructor-arg index=”0” type=”java.lang.String” value=”xxx”/>//     

   <property name=”name” value=”wxy”/>//  setter    

</bean>

 
 
 

bean:

  :

<bean id=”orderDao” class=”com.wxy.service.OrderDaoBean”/>

<bean id=”orderService” class=”com.wxy.service.OrderServiceBean”>

<property name=”orderDao” ref=”orderDao”/>

 </bean>

 
 
방법 2: (내부 bean 을 사용 하지만 이 bean 은 다른 bean 에 의 해 사용 할 수 없습니다)
<bean id=”orderService” class=”com.wxy.service.OrderServiceBean”>

      <property name=”orderDao”>

           <bean class=”com.wxy.service.OrderDaoBean”/>

      </property>

</bean>

 
 
 
2. 주입 의존 (Dependency Injection)
의존 주입 이란 운행 기간 에 외부 용기 에서 동적 으로 의존 대상 을 구성 요소 에 주입 하 는 것 을 말한다.
 
 
3. 인 코딩 은 주입 기능 에 의존 합 니 다.
1. beans. xml 을 수정 하고 의존 설정 을 추가 합 니 다.
 <?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

         <bean id="peopleDao" class="com.wxy.dao.impl.PeopleDaoBean"></bean>

         <bean id="peopleService" class="com.wxy.service.impl.PeopleServiceBean">

         <property name="peopleDap" ref="peopleDao"></property>

         <property name="xx" ref="xxDao"></property>

         </bean>

</beans>

 1.1
 
 
dao 클래스 만 들 기:
package com.wxy.dao.impl;

import com.wxy.dao.PeopleDao;

/**

*   Dao ,           

*   @create-time     2011-8-10     07:25:26   

*   @revision          $Id

*/

public class PeopleDaoBean implements PeopleDao {


    /* (non-Javadoc)

     * @see com.wxy.dao.impl.PeopleDao#add()

     */

    public void add() {

        System.out.println("this is the method PeopleDaoBean.add()!");

    }

}

 
 
 
 
   1.2 dao 인터페이스 만 들 기:
package com.wxy.dao;

public interface PeopleDao {

    public abstract void add();

}


 
 
 
 
2. 새로운 Property Definition 클래스, bean 의 property 속성 저장:
package com.wxy.bean;

 

/**

*     bean property   

*   @create-time     2011-8-10     04:40:07   

*   @revision          $Id

*/

public class PropertyDefinition {

    private String name; //   
   private String ref;  //      


    /**

     * @return the name

     */

    public String getName() {

        return name;

    }

    /**

     * @param name the name to set

     */

    public void setName(String name) {

        this.name = name;

    } 

    /**

     * @return the ref

     */

    public String getRef() {

        return ref;

    }

    /**

     * @param ref the ref to set

     */

    public void setRef(String ref) {

        this.ref = ref;

    }

    public PropertyDefinition(String name, String ref) {

        super();

        this.name = name;

        this.ref = ref;

    }

}

 
 
 
2.1. BeanDefinition 에 Property List 속성 을 추가 하고 property 목록 을 저장 합 니 다.
package com.wxy.bean;

 

import java.util.ArrayList;

import java.util.List;

 

public class BeanDefinition {

    private String                   id;

    private String                   className;

    private List<PropertyDefinition> properties = new       ArrayList<PropertyDefinition>(); //  bean      

    public BeanDefinition(String id, String className) {

        this.id = id;

        this.className = className;

    }


    /**

     * @return the id

     */

    public String getId() {

        return id;

    }


    /**

     * @param id the id to set

     */

    public void setId(String id) {

        this.id = id;

    }

    /**

     * @return the className

     */

    public String getClassName() {

        return className;

    }

    /**

     * @param className the className to set

     */

    public void setClassName(String className) {

        this.className = className;

}

/**

     * @return the properties

     */

    public List<PropertyDefinition> getProperties() {

        return properties;

    }

    /**

     * @param properties the properties to set

     */

    public void setProperties(List<PropertyDefinition> properties) {

        this.properties = properties;

    }
}

 
 
 
 
  2.2 peopleServiceBean 을 설정 하여 주입 기능 을 실현 합 니 다.
package com.wxy.service.impl;

 

import com.wxy.dao.PeopleDao;

import com.wxy.service.PeopleService;

 

/**

*   PeopleServiceBean

*   @create-time     2011-8-9     11:07:03   

*   @revision          $Id:PeopleServiceBean.java

*/

public class PeopleServiceBean implements PeopleService {

    private PeopleDao peopleDao;

 
    /**

     * @return the peopleDao

     */

    public PeopleDao getPeopleDao() {

        return peopleDao;

    }

    public void save() {

        System.out.println("--> the method is called save()!");

        peopleDao.add();

    }

    /**

     * @param peopleDao the peopleDao to set

     */

    public void setPeopleDao(PeopleDao peopleDao) {

        this.peopleDao = peopleDao;

    }
}

 
 
 
 
3. WxyClassPathXMLapplicationContext 에 들 어가 면 자신의 인 코딩 은 내부 주입 기능 에 의존 합 니 다.
 package com.wxy.content;

 

import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

import java.net.URL;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.XPath;

import org.dom4j.io.SAXReader;

 

import com.wxy.bean.BeanDefinition;

import com.wxy.bean.PropertyDefinition;

 

/**

*     IoC   

*  BeanDefinition resource  :readXML();

*  BeanDefinition       :readXML();

*  BeanDefinition IoC       instanceBeans();

*   @create-time     2011-8-10     09:19:17   

*   @revision          $Id

*/

public class WxyClassPathXMLApplicationContext {

 

    //  BeanDefinition   , beans.xml    bean      

    private final List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();

    //       ,    Bean     Map 

    private final Map<String, Object>  sigletons   = new HashMap<String, Object>();

 

    public WxyClassPathXMLApplicationContext(String fileName) {

        //  xml    

        this.readXML(fileName);

        //   bean

        this.instanceBeans();

        //    

        this.injectObject();

    }

 

    /**

     *       

     */

    private void injectObject() {

        for (BeanDefinition beanDefinition : beanDefines) {

            //  beanDefines    

            Object bean = sigletons.get(beanDefinition.getId());

            if (bean != null) {

                //    ,          

                try {

                    PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass())

                        .getPropertyDescriptors();

                    for (PropertyDefinition propertyDefinition : beanDefinition.getProperties()) {

                        for (PropertyDescriptor properdesc : ps) {

                            //       propertyDefinition       

                            if (propertyDefinition.getName().equals(properdesc.getName())) {

                                //     setter  

                                Method setter = properdesc.getWriteMethod();

                                if (setter != null) {

                                    Object value = sigletons.get(propertyDefinition.getRef());

                                    //          

                                    setter.setAccessible(true);//       

                                    setter.invoke(bean, value);

                                }

                            }

                        }

                    }

                } catch (SecurityException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                } catch (IllegalArgumentException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                } catch (IntrospectionException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                } catch (IllegalAccessException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                } catch (InvocationTargetException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            }

        }

    }

 

    /**

     *   XML    ,  BeanDefinition  ,   beanDefinition   

     * @param fileName xml      

     */

 

    private void readXML(String fileName) {

        SAXReader saxReader = new SAXReader();

        Document document = null;

        try {

            //        Resource    ,  BeanDefinition resource  

            URL xmlPath = this.getClass().getClassLoader().getResource(fileName);

            // xml   document 

            document = saxReader.read(xmlPath);

            Map<String, String> nsMap = new HashMap<String, String>();

            //      

            nsMap.put("ns", "http://www.springframework.org/schema/beans");

            //  beans/bean    ,  :          ,    

            XPath xsub = document.createXPath("//ns:beans/ns:bean");

            //      

            xsub.setNamespaceURIs(nsMap);

            //        Bean  

            List<Element> beans = xsub.selectNodes(document);

            for (Element element : beans) {

                //  id   

                String id = element.attributeValue("id");

                //  class   

                String clazz = element.attributeValue("class");

                BeanDefinition beanDefinition = new BeanDefinition(id, clazz);

                //  bean/property    

                XPath propertysub = element.createXPath("ns:property");

                //      

                propertysub.setNamespaceURIs(nsMap);

                //  bean property    

                List<Element> properties = propertysub.selectNodes(element);

                for (Element property : properties) {

                    String propertyName = property.attributeValue("name");

                    String propertyref = property.attributeValue("ref");

                    PropertyDefinition propertyDefinition = new PropertyDefinition(propertyName,

                        propertyref);

                    System.out.println(property);

                    // property     beanDefinition 

                    beanDefinition.getProperties().add(propertyDefinition);

                }

                //     BeanDefinition  ing   BeanDeifnitions 

                beanDefines.add(beanDefinition);

            }

        } catch (Exception e) {

            System.out.println(e.toString());

        }

    }

 

    /**

     *    bean,   sigletons 

     */

    private void instanceBeans() {

        for (BeanDefinition beanDefinition : beanDefines) {

            try {

                if (beanDefinition.getClassName() != null

                    && !(beanDefinition.getClassName().isEmpty())) {

                    //  java    ,  BeanDefinition  ,      sigletons 

                    sigletons.put(beanDefinition.getId(), Class.forName(

                        beanDefinition.getClassName()).newInstance());

                }

            } catch (Exception e) {

                e.printStackTrace();

            }

        }

 

    }

 

    /**

     *   ID     bean

     * return     Object  ,     ,              

     */

    public Object getBean(String beanName) {

        return this.sigletons.get(beanName);

    }

} 


 
 
 
  property 의 속성 값 을 찾 았 는 지 테스트 합 니 다:
public class Test {

 

    public static void main(String[] args) {

        //IOC     

        WxyClassPathXMLApplicationContext ac = new WxyClassPathXMLApplicationContext("beans.xml");

        PeopleService peopleService = (PeopleService) ac.getBean("peopleService");

        peopleService.save();

    }

}

 테스트 결과:
---------------------------------------
--> the method is called save()!this is the method PeopleDaoBean.add()!
----------------------------------------
 
 

좋은 웹페이지 즐겨찾기