揭秘Spring扫描注解实例化本质

模仿Spring通过扫描注解来实例化对象(基于反射实现)

1. 自定义一个注解和两个待实例化的类Bean,Demo,待会要用

package ZhuJie;

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

@Target(ElementType.FIELD)//声明注解用于域
@Retention(RetentionPolicy.RUNTIME)//表明注解保存在运行期
public @interface CCBean {
}


package ZhuJie;

public class Bean {
    public Bean(){
        System.out.println(" sBean  construction------");
    }
    public String s = "hello world";

    public String getS() {
        return s;
    }
    private void test(){}

    public void setS(String s) {
        this.s = s;
    }
    public void setQA(int c){}
    public void setQA(int c ,int b,String a){}
}


public class Demo{
    public Demo(){
        System.out.println("Demo construction ---");
    }
}

2. Controller层声明Bean类型

package ZhuJie;

public class Controller {
    @CCBean
    public Bean bean;

    public Demo demo;
}

3.注解处理器(核心代码)

package ZhuJie;

import java.lang.reflect.Field;

public class Zjdeal {
      public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
      Field[] fields  =  Controller.class.getDeclaredFields();
     for (Field meo : fields){
          CCBean ccBean = meo.getAnnotation(CCBean.class);
          if(!(ccBean == null)) {//判断添加注解的域
                String ca = meo.getGenericType().getTypeName();
                Class.forName(ca).newInstance();
           }
        }
     }
}

4.结果

揭秘Spring扫描注解实例化本质_第1张图片
添加了@CCBean的注解被成功实例化
*原创文章,转载请注明出处,更多技术讨论可以加群262907651
*

你可能感兴趣的:(java,spring)