springIOC

作者: 健倾心语 | 来源:发表于2018-12-05 17:05 被阅读9次

springIOC控制反转:将每个bean于bean之间的关系交给第三方容器spring进行管理
springIOC原理:dom4j+java的反射机制
1.解析xml
2.使用bean id查找对应的xml节点,获取class节点属性
3.使用java的反射机制初始化类
4.使用java反射机制给私有属性赋值

反射机制缺点:初始化对象效率低,耗资源
优点:扩展性高
例子:
applicationContext.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" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="    
     http://www.springframework.org/schema/beans     
     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
     http://www.springframework.org/schema/tx     
     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    
     http://www.springframework.org/schema/aop     
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    
     http://www.springframework.org/schema/context    
     http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="user1" class="com.crj.entity.UserEntity">
        <property name="userId" value="0002"></property>
        <property name="userName" value="张三"></property>
    </bean>
    <bean id="user2" class="com.crj.entity.UserEntity">
        <property name="userId" value="0003"></property>
        <property name="userName" value="李四"></property>
    </bean>


</beans>   

UserEntity.java

package com.crj.entity;

/**   
 * @author: crj
 * @date: 2018年12月5日 下午3:36:18 
 */
public class UserEntity {
    private String userId;
    private String userName;
    
    
    public String getUserId() {
        return userId;
    }


    public void setUserId(String userId) {
        this.userId = userId;
    }


    public String getUserName() {
        return userName;
    }


    public void setUserName(String userName) {
        this.userName = userName;
    }


    @Override
    public String toString() {
        return "UserEntity [userId=" + userId + ", userName=" + userName + "]";
    }
    
    
    
    

}

ClassPathXmlApplicationContext.java

package com.crj;

import java.lang.reflect.Field;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.crj.entity.UserEntity;

/**   
 * @author: crj
 * @date: 2018年12月5日 下午3:57:25 
 */
public class ClassPathXmlApplicationContext {
    private String PATH;
    private String ID;
    private String CLASS;
    private String NAME;
    private String VALUE;
    public void init() {
        ID = "id";
        CLASS ="class";
        NAME = "name";
        VALUE = "value";
    }
    public ClassPathXmlApplicationContext(String path) {
        this.PATH = path;
    }
    public Object getBean(String beanId) throws DocumentException, ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException {
        init();
        //      1.解析xml
        if(StringUtils.isEmpty(beanId)) {
            return null;
        }
        
        SAXReader saxReader = new SAXReader();
        Document read = saxReader.read(this.getClass().getClassLoader().getResource(PATH));
        Element rootElement = read.getRootElement();
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            String id = element.attributeValue(ID);
            if(!beanId.equals(id)) {
                continue;//结束本次循环
            }
//          2.使用bean id查找对应的xml节点,获取class节点属性
            String attClass = element.attributeValue(CLASS);
//          3.使用java的反射机制初始化类
            Class<?> forName = Class.forName(attClass);
            Object newInstance = forName.newInstance();
            List<Element> elements2 = element.elements();
            for (Element element2 : elements2) {
                String attField = element2.attributeValue(NAME);
                String attValue = element2.attributeValue(VALUE);
                Field declaredField = forName.getDeclaredField(attField);
                declaredField.setAccessible(true);
//              4.使用java反射机制给私有属性赋值
                declaredField.set(newInstance, attValue);
            }
            return newInstance;
            
        }
        return null;
    }
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException, DocumentException {
        ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserEntity user = (UserEntity) app.getBean("user1");
        System.out.println(user.toString());
    }

}

相关文章

  • 手写springioc

    手写简易springIOC springIOC的特点 spring ioc,spring容器,根据xml配置,或者...

  • spring源码解析之SpringIOC源码解析(上)

    SpringIOC源码解析(上) 一、什么是SpringIOC spring ioc指的是控制反转,IOC容器负责...

  • spring bean 生命周期

    springIOC 容器中bean 的生命周期方法 springioc容器可以管理bean的生命周期,spring...

  • springIoc

    1、Ioc(Inverse of control,控制反转) 控制:指对象的控制权 反转:控制权从调用类中移除,由...

  • SpringIOC

    Spring的控制反转(IOC) 把对象的创建初始化、销毁等工作交给spring容器来做,由spring容器来控制...

  • springIOC

    IOC的组成体系结构 1、资源定位(配置文件定位) 2、载入(读取配置文件) 3、注册(把加载以后的配置文件解释成...

  • SpringIOC

    SpringIOC 博客链接 概述 IOC,全称"Inverse Of Control",中文意思为:控制反转。那...

  • SpringIOC

    基本概念 IoC是什么? 如果这个问题要是面试的问题,那么我会这么回答。 IoC(Inversion of Con...

  • SpringIOC

    配置bean class: bean 的全类名,通过反射的方式在IOC容器中创建Bean,所以要求Bean中必须有...

  • SpringIOC

    作为一个容器,通过配置文件或者注解描述类与类之间的依赖关系,自动完成类的初始化和依赖注入的工作 Spring的核心...

网友评论

      本文标题:springIOC

      本文链接:https://www.haomeiwen.com/subject/kxlicqtx.html