• 自己写一个注解 代替@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(); } }
  • 相关阅读:
    原创 计算机系学生大学四年应该这样过
    ff3f34fq34f
    指针 引用
    POJ3352Road Construction
    POJ3308Paratroopers
    北大ACM试题分类 实时更新我所有的解题报告链接
    POJ2516Minimum Cost
    【转】一位ACMer过来人的心得
    POJ2528Mayor's posters
    POJ2186Popular Cows
  • 原文地址:https://www.cnblogs.com/wangxiaomei/p/16252660.html
Copyright © 2020-2023  润新知