自己写一个注解 代替@Autowire

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Inherited
@Documented
public @interface MyAutowire {
}

 

public class TestController {

    @MyAutowire
    private TestService testService;

    public void testControllerMethod(){
        testService.testserviceMethod();
    }

}

 

public class TestService {

    public void testserviceMethod(){
        System.out.println("我是service");
    }
}

 

public class Test {

    public static void main(String[] args) {
        TestController testController=new TestController();
        Class clazz=testController.getClass();
        Field[] fields =clazz.getDeclaredFields();
        for(Field field:fields){
           Annotation annotation= field.getAnnotation(MyAutowire.class);
           if(annotation!=null){
               Class type=field.getType();
               try {
                   //必须设置为可访问 否则会报错
                   field.setAccessible(true);
                   Object o=type.newInstance();
                   //拿到这个属性 向对象的这个属性设置值
                   field.set(testController,o);
               } catch (InstantiationException e) {
                   e.printStackTrace();
               } catch (IllegalAccessException e) {
                   e.printStackTrace();
               }
           }
        }
      
     //可以成功输出 service的打印的 我是service testController.testControllerMethod(); } }

 

posted @ 2022-05-10 11:09  小梅子呀  阅读(57)  评论(0编辑  收藏  举报