您的位置:首页 > 编程语言 > Java开发

java 反射 模拟spring自动注入

2017-01-13 16:44 337 查看
基于反射和注解机制,简单模拟spring解析Autowired注解的过程。

1、自定义Autowired注解,代码如下

[java] view
plain copy

package com.basic.reflect;  

  

import java.lang.annotation.ElementType;    

import java.lang.annotation.Retention;    

import java.lang.annotation.RetentionPolicy;    

import java.lang.annotation.Target;    

  

@Retention(RetentionPolicy.RUNTIME)  

@Target({ ElementType.FIELD, ElementType.METHOD })  

public @interface Autowired {  

    //注解的name属性    

    public String name() default "";    

}  

2、定义相关的业务和Dao类,以及获取Bean的容器(在容器中基于反射实现自动注入)

[java] view
plain copy

 





public class PersonDao {  

    public int add(Object o) {  

        System.out.println("dao autowird ok ");  

        return 0;  

    }  

}  

public class ServiceImpl {  

    @Autowired  

    private PersonDao personDao;  

  

    public int addPerson(Object obj) {  

        return personDao.add(obj);  

    }  

}  

public class BeanContainer {  

    public static Object getBean(String name) {  

        try {  

            Class<?> clazz = Class.forName("com.basic.reflect.ServiceImpl");  

            Object bean = clazz.newInstance();  

            Field[] fileds = clazz.getDeclaredFields();  

            for (Field f : fileds) {  

                if (f.isAnnotationPresent(Autowired.class)) {                          

                    // 基于类型注入  

                    Class<?> c = f.getType();  

                    Object value = c.newInstance();  

                    //允许访问private字段    

                    f.setAccessible(true);    

                    //把引用对象注入属性    

                    f.set(bean, value);                            

                }  

            }  

            return bean;  

        } catch (Exception e) {  

            e.printStackTrace();  

        }  

        return null;  

    }  

}   

3、测试

[java] view
plain copy

 





public class Test {  

    public static void main(String[] args) {  

        ServiceImpl impl = (ServiceImpl) BeanContainer.getBean("service");  

        String name = "test";  

        impl.addPerson(name);  

    }  

}  



总结,上面的代码简单模拟了Spring解析Autowired的过程,写的比较简单,但是精髓已经写到了,主要就是利用反射机制生成实例并且解析注解对其属性进行赋值。其实Spring框架的核心Ioc和Aop的实现,还是利用了Java最基本的东西,比如Aop就是利用了动态代理,Ioc就是利用了反射机制
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java反射