1. 程式人生 > >手寫SpringIOC容器框架

手寫SpringIOC容器框架

1.使用xml方式注入物件

匯入依賴:

<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>
/**
 * Created by yz on 2018/6/3.
 */
public interface OrderService {
    public void 
addOrder(); }
/**
 * Created by yz on 2018/6/3.
 */
//@ExtService
public class OrderServiceImpl implements OrderService {
    @Override
    public void addOrder() {
        System.out.println("使用Java反射機制初始化物件...");
    }
}

spring.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.xsd"> <bean id="orderService" class="com.yz.ioc.service.Impl.OrderServiceImpl"/> </beans>
import org.dom4j.Document;
import 
org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.springframework.util.StringUtils; import java.io.InputStream; import java.util.List; /** * 自定義spring容器框架 xml方式實現 * Created by yz on 2018/6/3. */ public class ExtClassPathXmlApplicationContext { // xml讀取路徑地址 private String xmlPath; public ExtClassPathXmlApplicationContext(String xmlPath) { this.xmlPath = xmlPath; } public Object getBean(String beanId) throws Exception { if(StringUtils.isEmpty(beanId)){ return new Exception("bendId不能為空"); } // 1.解析xml,獲取所有bean節點資訊 List<Element> readerxml = readeXml(xmlPath); // 2.使用方法引數bend id查詢配置檔案中bean節點的id資訊是否一致。 if(readerxml == null || readerxml.isEmpty()){ return new Exception("配置檔案中,沒有配置bean資訊"); } String className = findByElementClass(readerxml, beanId); if(StringUtils.isEmpty(className)){ return new Exception("bean物件沒有配置class地址"); } // 3.獲取class資訊地址,使用反射機制初始化 return newInstance(className); } // 重構 public String findByElementClass(List<Element> readerxml,String beanId) throws Exception { for (Element element : readerxml) { // 獲取屬性資訊 String xmlbeanId = element.attributeValue("id"); if(StringUtils.isEmpty(xmlbeanId)){ continue; } if(xmlbeanId.equals(beanId)){ String xmlClassPath = element.attributeValue("class"); return xmlClassPath; } } return null; } // 根據路徑通過反射機制獲取物件 public Object newInstance(String className) throws Exception { Class<?> classInfo = Class.forName(className); return classInfo.getDeclaredConstructor().newInstance(); } // 解析xml public List<Element> readeXml(String xmlPath) throws DocumentException { // 1.解析xml資訊 SAXReader saxReader = new SAXReader(); Document document = saxReader.read(getResourcesAsStream(xmlPath)); // 2.讀取節點下所有的子節點 Element rootElement = document.getRootElement(); // 3.獲取根節點下所有的子節點 List<Element> elements = rootElement.elements(); return elements; } // 獲取當前上下文 public InputStream getResourcesAsStream(String xmlPath){ InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(xmlPath); return inputStream; } }
import com.yz.ioc.ExtClassPathXmlApplicationContext;
import com.yz.ioc.service.OrderService;

/**
 * 測試ioc程式碼
 * Created by yz on 2018/6/3.
 */
public class IOCTest {
    public static void main(String[] args) throws Exception {
        ExtClassPathXmlApplicationContext context = new ExtClassPathXmlApplicationContext("spring.xml");
        OrderService orderService = (OrderService) context.getBean("orderService");
        orderService.addOrder();
    }
}

2.使用註解方式注入物件 AOP IOC實現

spring.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--使用自定義註解方式,掃包範圍-->
    <context:component-scan base-package="com.yz.ioc"/>

</beans>

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 自定義@Service註解 注入bean容器
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtService {
}
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 自定義@Resource註解 注入bean容器
 */
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface ExtResource {
}
/**
 * Created by yz on 2018/6/3.
 */
public interface OrderService {
    void addOrder();
}
/**
 * Created by yz on 2018/6/3.
 */
@ExtService
public class OrderServiceImpl implements OrderService {
    @Override
    public void addOrder() {
        System.out.println("使用註解方式依賴注入...");
    }
}
/**
 * Created by yz on 2018/6/3.
 */
public interface UserService {
    void add();
}
import com.yz.ioc.annotation.ExtResource;
import com.yz.ioc.annotation.ExtService;
import com.yz.ioc.service.OrderService;
import com.yz.ioc.service.UserService;

/**
 * Created by yz on 2018/6/3.
 */
@ExtService
public class UserServiceImpl implements UserService {

    @ExtResource
    private OrderService orderService;

    @Override
    public void add(){
        orderService.addOrder();
    }

}
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 類相關的工具類
 * Created by yz on 2018/6/3.
 */
public class ClassUtil {

    /**
     * 從包package中獲取所有的Class
     * @param packageName
     * @return
     */
    public static List<Class<?>> getClasses(String packageName){

        //第一個class類的集合
        List<Class<?>> classes = new ArrayList<Class<?>>();
        //是否迴圈迭代
        boolean recursive = true;
        //獲取包的名字 並進行替換
        String packageDirName = packageName.replace('.', '/');
        //定義一個列舉的集合 並進行迴圈來處理這個目錄下的things
        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            //迴圈迭代下去
            while (dirs.hasMoreElements()){
                //獲取下一個元素
                URL url = dirs.nextElement();
                //得到協議的名稱
                String protocol = url.getProtocol();
                //如果是以檔案的形式儲存在伺服器上
                if ("file".equals(protocol)) {
                    //獲取包的物理路徑
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    //以檔案的方式掃描整個包下的檔案 並新增到集合中
                    findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
                } else if ("jar".equals(protocol)){
                    //如果是jar包檔案
                    //定義一個JarFile
                    JarFile jar;
                    try {
                        //獲取jar
                        jar = ((JarURLConnection) url.openConnection()).getJarFile();
                        //從此jar包 得到一個列舉類
                        Enumeration<JarEntry> entries = jar.entries();
                        //同樣的進行迴圈迭代
                        while (entries.hasMoreElements()) {
                            //獲取jar裡的一個實體 可以是目錄 和一些jar包裡的其他檔案 如META-INF等檔案
                            JarEntry entry = entries.nextElement();
                            String name = entry.getName();
                            //如果是以/開頭的
                            if (name.charAt(0) == '/') {
                                //獲取後面的字串
                                name = name.substring(1);
                            }
                            //如果前半部分和定義的包名相同
                            if (name.startsWith(packageDirName)) {
                                int idx = name.lastIndexOf('/');
                                //如果以"/"結尾 是一個包
                                if (idx != -1) {
                                    //獲取包名 把"/"替換成"."
                                    packageName = name.substring(0, idx).replace('/', '.');
                                }
                                //如果可以迭代下去 並且是一個包
                                if ((idx != -1) || recursive){
                                    //如果是一個.class檔案 而且不是目錄
                                    if (name.endsWith(".class") && !entry.isDirectory()) {
                                        //去掉後面的".class" 獲取真正的類名
                                        String className = name.substring(packageName.length() + 1, name.length() - 6);
                                        try {
                                            //新增到classes
                                            classes.add(Class.forName(packageName + '.' + className));
                                        } catch (ClassNotFoundException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return classes;
    }

    /**
     * 以檔案的形式來獲取包下的所有Class
     * @param packageName
     * @param packagePath
     * @param recursive
     * @param classes
     */
    public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, List<Class<?>> classes){
        //獲取此包的目錄 建立一個File
        File dir = new File(packagePath);
        //如果不存在或者 也不是目錄就直接返回
        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }
        //如果存在 就獲取包下的所有檔案 包括目錄
        File[] dirfiles = dir.listFiles(new FileFilter() {
            //自定義過濾規則 如果可以迴圈(包含子目錄) 或則是以.class結尾的檔案(編譯好的java類檔案)
            public boolean accept(File file) {
                return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
            }
        });
        //迴圈所有檔案
        for (File file : dirfiles) {
            //如果是目錄 則繼續掃描
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "." + file.getName(),
                        file.getAbsolutePath(),
                        recursive,
                        classes);
            }
            else {
                //如果是java類檔案 去掉後面的.class 只留下類名
                String className = file.getName().substring(0, file.getName().length() - 6);
                try {
                    //新增到集合中去
                    classes.add(Class.forName(packageName + '.' + className));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
import com.yz.ioc.annotation.ExtResource;
import com.yz.ioc.annotation.ExtService;
import com.yz.ioc.uitl.ClassUtil;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 自定義spring容器框架 註解方式實現
 * Created by yz on 2018/6/3.
 */
public class ExtClassPathXmlApplicationContext {

    // 定義springbean容器
    private ConcurrentHashMap<String,Object> beans;

    // 掃包的範圍
    private String packageName;

    public ExtClassPathXmlApplicationContext(String xmlPath) throws Exception {
        // 初始化引數
        beans = new ConcurrentHashMap<>();
        this.packageName = getPackageName(xmlPath);
        initBeans();
        initEntryField();
    }

    // 初始化屬性
    private void initEntryField() throws Exception {
        // 1.遍歷所有bena容器物件
        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            // 2.判斷屬性上面是否有加註解
            Object object = entry.getValue();
            inversionOfControl(object);
        }
    }

    public Object getBean(String beanId) throws Exception {
        System.out.println(beanId);
        if(StringUtils.isEmpty(beanId)){
            throw new Exception("beanId引數不能為空");
        }
        // spring容器獲取bean
        Object object = beans.get(beanId);
        return object;
    }

    // 根據路徑通過反射機制獲取物件
    public Object newInstance(Class<?> classInfo) throws Exception {
        return classInfo.getDeclaredConstructor().newInstance();
    }

    // 初始化物件
    public void initBeans() throws Exception {
        // 1.使用Java的反射機制掃包,獲取當前包下所有的類
        List<Class<?>> classes = ClassUtil.getClasses(packageName);
        // 2.判斷類上是否存在注入bean的註解
        ConcurrentHashMap<String, Object> classIsAnnotation = findClassIsAnnotation(classes);
        if(classIsAnnotation == null || classIsAnnotation.isEmpty()){
            throw new Exception("該包下沒有任何類加上註解");
        }
    }

    // 判斷類上是否存在注入bean的註解
    public ConcurrentHashMap<String,Object> findClassIsAnnotation(List<Class<?>> classes) throws Exception {
        for (Class<?> classInfo : classes) {
            // 判斷類上是否有註解
            ExtService annotation = classInfo.getAnnotation(ExtService.class);
            if(annotation !=null){
                // 獲取當前類名,beanid 預設類名小寫
                String className = classInfo.getSimpleName();
                String beanId = toLowerCaseFirstOne(className);
                // 通過反射機制建立物件
                Object newInstance = newInstance(classInfo);
                beans.put(beanId,newInstance);
                continue;
            }
        }
        return beans;
    }

    //首字母轉小寫
    public static String toLowerCaseFirstOne(String s){
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder())
                    .append(Character.toLowerCase(s.charAt(0)))
                    .append(s.substring(1)).toString();
    }

    // 讀取xml中配置的包路徑
    public String getPackageName(String xmlPath) throws Exception {
        SAXReader saxReader = new SAXReader();
        // 讀取xml檔案
        Document document = saxReader.read(getResourcesAsStream(xmlPath));
        // 讀取節點
        Element rootElement = document.getRootElement();
        // 獲取根節點下所有的子節點
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            if(element.getName().equals("component-scan")){
                // 獲取掃包路徑
                Attribute attribute = element.attribute("base-package");
                return attribute.getText();
            }
        }
        return null;
    }

    public InputStream getResourcesAsStream(String xmlPath){
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(xmlPath);
        return inputStream;
    }

    // 依賴注入
    public void inversionOfControl(Object object) throws Exception {
        // 依賴注入實現原理
        // 1.使用反射機制,獲取當前類的所有屬性
        Class<?> classInfo = object.getClass();
        Field[] fileds = classInfo.getDeclaredFields();
        // 2.判斷當前類屬性是否存在註解
        for (Field filed : fileds) {
            // 3.預設使用屬性名稱,查詢bean容器物件
            ExtResource extResource = filed.getAnnotation(ExtResource.class);
            if(extResource !=null){
                // 獲取屬性名稱
                String beanId = filed.getName();
                Object bean = getBean(beanId+"Impl");
                if(bean != null){
                    // 允許訪問私有屬性
                    filed.setAccessible(true);
                    // 屬性賦值
                    filed.set(object,bean);
                }
            }
        }
    }

}
/**
 * Created by yz on 2018/6/3.
 */
public class IOCTest {
    public static void main(String[] args) throws Exception {
        ExtClassPathXmlApplicationContext context = new ExtClassPathXmlApplicationContext("spring.xml");
//        OrderService orderService = (OrderService) context.getBean("orderServiceImpl");
//        orderService.addOrder();
        UserService userService = (UserService) context.getBean("userServiceImpl");
        userService.add();
    }
}