热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

@Autowired自动装配的简单实现

测试类,模拟Controller调用***模拟Controller**publicclassMyController{MyAutowiredprivateMySe

测试类,模拟Controller调用

/*** 模拟@Controller* */
public class MyController {@MyAutowiredprivate MyService myService;public void print(){String name = myService.getName();System.out.println(name);}
}

自动装配测试:

public class AutowiredTest {public static void main(String[] args) {MyController myController = new MyController();//简单的自动装配reflect(myController);myController.print();}//传入需要专配的对象public static void reflect(Object obj) {Class clazz = obj.getClass();Field[] fields = clazz.getDeclaredFields();for (Field field : fields) {//获取属性 是否有注解MyAutowired annotation = field.getAnnotation(MyAutowired.class);if (annotation != null) {field.setAccessible(true);//获取当前属性的类型,有了类型后可以创建具体对象Class type = field.getType();//创建具体对象Object o = null;try {o = type.newInstance();field.set(obj, o);} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}}}
}

自定义注解:

//作用范围
@Retention(RetentionPolicy.RUNTIME)
//作用目标
@Target(ElementType.FIELD)
//继承
@Inherited
//文档记录
@Documented
public @interface MyAutowired {
}

模拟Service层:

public class MyService {public String getName() {return "PersonService.getName()";}
}


推荐阅读
author-avatar
碧桃玉李
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有