仿spring中的Bean注解与Value注解所实现的功能

大体思路

  1. 获取指定文件夹下的所有类
  2. 遍历所有类检查每一个类有无指定注解
  3. 如有对应的注解则进行对应的操作

最后返回的是一个map集合

先定义一个Map集合,目的就是通过类名key拿到对应的对象value

private Map<String,Object> map;

Bean注解功能

//获取domain目录路径
String path = getClass().getResource("domain").getPath();
/**获取domain类中的全限定名前缀*/
    //去掉前面的的路径
String replace = path.replace(path1, "");
    //把 "/" 全部替换为 "."
replace = replace.replace("/", ".");
    //最后在末尾加上一个.,即有了类的全限定名的前缀
String main = replace + ".";
//转成文件类型
File file1 = new File(path);
//获取该文件下的所有文件
File[] files1 = file1.listFiles();

获取项目根路径
String path = getClass().getResource(“/”).getPath();

//遍历文件(也就是遍历类)
try {
    for (File F : files1) {
        /**因为获取到的名字是  对象名.class  所以要进行处理*/
            //获取最后一个.所在的索引位置
        int i = F.getName().lastIndexOf(".");
            //把前面的类名截取出来
        String substring = F.getName().substring(0,i);
            //设置全限定名的字符串
        String newClass = main + substring;

        //获取字节码对象
        Class<?> aClass = Class.forName(newClass);
        //根据字节码对象获取指定注解
        boolean annotationPresent1 = aClass.isAnnotationPresent(Component.class);
        //如果为false即为没有对应的注解
        if(annotationPresent1){
            //创建对象并存入Map
            Object o = aClass.newInstance();
            //名字以获得的类名作为key
            map.put(substring,o);
        }

Value注解功能

        //根据字节码对象获取该对象的所有字段
        Field[] declaredFields = aClass.getDeclaredFields();

        for (Field declaredField : declaredFields) {
            //判断有无该注解
            boolean annotationPresent = declaredField.isAnnotationPresent(Value.class);
            if (annotationPresent) {
                //获取注解设置的值
                String value = declaredField.getAnnotation(Value.class).value();
                //获取属性名字
                String d = declaredField.getName();

                /**
                 * 下面就是内省
                 */
                //获取属性描述器
                BeanInfo beanInfo = Introspector.getBeanInfo(aClass);
                //获取所有属性
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                for (PropertyDescriptor p : propertyDescriptors) {
                    //对比属性名,如果匹配上那么就设置注解的值
                    if (d.equals(p.getName())) {
                        //获取set方法
                        Method writeMethod = p.getWriteMethod();
                        //对上面创建出来的对象进行赋值
                        writeMethod.invoke(map.get(substring),value);
                    }
                }
            }
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}
System.out.println(map);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值