依赖注入实现

xml方式

测试类

public static void main(String[] args){
        ApplicationContextXml applicationContext = new ApplicationContextXml("haoziContext.xml");
        UserDao userDao = (UserDao) applicationContext.getBean("userDao");
    }

ApplicationContextXml

package com.haozi.application;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.XmlUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ApplicationContextXml {

    private String path;
    private Map<String,Object> beanContainer;
    /**
     *
     * @param path xml路径
     */
    public ApplicationContextXml(String path){
        this.path = path;
        beanContainer = new HashMap<String, Object>();
        try {
            try {
                loadBean();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            System.out.println("类名错误:"+e.getMessage());
        }
    }

    /**
     * 加载bean
     */
    private  void loadBean() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        //解析xml
        Document document =  XmlUtil.readXML(path);
        Element rootElement = document.getDocumentElement();
        List<Element> beansElement = XmlUtil.getElements(rootElement,"bean");
        for(Element elementItem:beansElement){
            String beanid = elementItem.getAttribute("id");
            String className = elementItem.getAttribute("class");
            Class clazz = Class.forName(className);

            beanContainer.put(beanid,clazz.newInstance());
        }
    }

    /**
     * 获取bean
     * @param beanId
     * @return
     */
    public Object getBean(String beanId){
        if(beanContainer.containsKey(beanId)){
            return beanContainer.get(beanId);
        }
        return null;
    }

}

xml

<beans>
    <!--dao层-->
    <bean id = "userDao" class = "com.haozi.dao.UserDao">
    </bean>
</beans>

注解实现

测试类

  public static void  main(String[] args){
        ApplicationContextAnnon applicationContextAnnon = new ApplicationContextAnnon("com.haozi");
        StudentService studentService =(StudentService)applicationContextAnnon.getBean("studentService");
        System.out.println(studentService);
    }

ApplicationContextAnnon

package com.haozi.application;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ReflectUtil;
import com.haozi.annon.AutoWired;
import com.haozi.annon.Service;
import com.haozi.util.ClassUtil;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.List;

public class ApplicationContextAnnon {
    private HashMap<String, Object> beansContainer;
    private String packageName;

    public ApplicationContextAnnon(String packageName) {
        this.packageName = packageName;
        beansContainer = new HashMap<String, Object>();
        //包扫描
        List<Class<?>> classList = ClassUtil.getClasses(packageName);
        //装载bean
        loadBean(classList);
        //注入
        injectProperties(classList);
    }

    /**
     * 通过beanid获取bean
     * @param beanId
     * @return
     */
    public Object getBean(String beanId){
        if(beansContainer.containsKey(beanId)){
            Object object = beansContainer.get(beanId);
            return object;
        }
        return null;
    }
    /**
     * 为属性注入
     * @param classList
     */
    private void injectProperties(List<Class<?>> classList) {
        for (Class clazz : classList) {
            //所有字段
            Field[] fields = ReflectUtil.getFields(clazz);
            for (Field field : fields) {
                //判断是否有AutoWired注解
                AutoWired autoWiredAnnon = (AutoWired)field.getDeclaredAnnotation(AutoWired.class);
                if (autoWiredAnnon!=null) {
                    String fieldName = field.getName();
                    if(beansContainer.containsKey(fieldName)){

                        Object object = beansContainer.get(fieldName);
                        //获取beanid
                        String beanId = classNameToLower(clazz.getSimpleName());
                        Object injectObj = beansContainer.get(beanId);
                        ReflectUtil.setFieldValue(injectObj,fieldName,object);
                    }
                }
            }
        }

    }

    /**
     * 装载bean
     * @param classList
     */
    private void loadBean(List<Class<?>> classList) {


        for (Class clazz : classList) {
            //获取注解列表
            Annotation[] annotations = clazz.getAnnotations();
            List<Annotation> list = CollectionUtil.newArrayList(annotations);
            //判断是否有AutoWired注解
            Service serviceAnnon = (Service)clazz.getDeclaredAnnotation(Service.class);
            //是否包含service注解
            if (serviceAnnon!=null) {
                //类名第一个字母小写作为id
                String beanId = classNameToLower(clazz.getSimpleName());
                try {
                    beansContainer.put(beanId, clazz.newInstance());
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }

        }

    }

    private String classNameToLower(String className) {
        char[] chars = className.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值