测试类,模拟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()";}
}