简单的仿写Spring Ioc

Ioc—Inversion of Control,即“控制反转”,不是什么技术,而是一种设计思想。在Java开发中,Ioc意味着将你设计好的对象交给容器控制,而不是传统的在你的对象内部直接控制

Spring中的Ioc简单来说就是用@Componnt之类的注解,把他交给Spring,然后用@Autowired或者@Resource之类的注解从Spring中拿出

首先写两个他的注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Autowired {
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
}

重点是接下来的如何存放和取出

public class SpringIOC {

    private List<String> beanNames;
    private List<String> filePaths;
    private String basePath;
    private String basePackage;
    private Map<String, Object> beans =new HashMap<>();
    /**
     * 扫描所有的文件信息信息,存到了 filePaths
     */
    private void scan() throws FileNotFoundException {
        File file = new File(basePath);
        filePaths = new ArrayList<>();
        if(file.exists()){
            Queue<File> queue = new LinkedList<>();
            queue.add(file);
            while(!queue.isEmpty()){
                File poll = queue.poll();
                if(poll == null){
                    continue;
                }
                if(poll.isDirectory()){
                    File[] files = poll.listFiles();
                    for (File f : files) {
                        queue.add(f);
                    }
                }else {
                    filePaths.add(poll.getPath());
                }
            }
        }else {
            throw new FileNotFoundException(basePath+" not found");
        }
    }

    /**
     * 讲所有的.java结尾的 全限定名放到 beanNames
     */
    public void  initBeanNames(){
        for (String s : filePaths) {
            String replace = s.replace(basePath, "");
            if(replace.endsWith(".java")) {
                replace = replace.substring(0, replace.length()-5);
            }

            char[] chars = replace.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                if(chars[i]=='\\'){
                    chars[i] = '.';
                }
            }
            beanNames.add(basePackage+"."+new String(chars));
        }
    }

    public void initBeans(){
        for (String beanName : beanNames) {
            try {
                Class<?> aClass = Class.forName(beanName);
                Annotation[] declaredAnnotations = aClass.getDeclaredAnnotations();
                for (Annotation declaredAnnotation : declaredAnnotations) {
                    if(declaredAnnotation instanceof Component){
                        Object o = aClass.newInstance();
                        beans.put(aClass.getName(),o);
                    }
                }
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }

        }

        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();

            for (Field field : declaredFields) {

                Annotation[] declaredAnnotations = field.getDeclaredAnnotations();

                for (Annotation annotation : declaredAnnotations) {
                    if(annotation instanceof Autowired ){
                        //field 需要由我们来赋值
                        // 我们所持有的所有对象 在beans中
                        // 根据当前域中的类型的名字
                        String name = field.getType().getName();
                        // 从beans 中获得对应的对象
                        Object o = beans.get(name);
                        field.setAccessible(true);
                        try {
                            field.set(entry.getValue(), o);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }


        }
    }
    public Object getInstance(String beanName) {
        return beans.get(beanName);
    }
    private void initPath(){
        //这是这个项目的路径
        basePath="E:\\xx\\xx\\";
        //上层的包名
        basePackage="com.heaboy.springioc";
    }
    
    //首先调用这里
    public SpringIOC() {
        // 初始化路径
        initPath();
        try {
            scan();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        beanNames= new ArrayList<>();
        initBeanNames();
    }
}

测试是

    @Test
    public void testScan() throws FileNotFoundException {
        SpringIOC springIOC = new SpringIOC();
        springIOC.initBeans();
        TestController instance = (TestController)springIOC.getInstance(TestController.class.getName());
        instance.test();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值