本文主要是介绍Spring框架十一、Spring IOC源码概述,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、Spring IOC Bean对象注入原理
Spring bean对象的注入,分为xml注入和注解注入,这两种方式都是利用反射来实现的。
1、xml方式注入
xml方式是通过反射找到类中的set方法,调用此方式实现注入的:
UserService.java
public class UserService {
}
UserController.java
public class UserController {private UserService userService;public void setUserService(UserService userService) {this.userService = userService;}public UserService getUserService() {return userService;}
}
测试类
public class MyTest {public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {UserController userController = new UserController();//获取class信息Class clazz = userController.getClass();//获取变量名Field userServiceField = clazz.getDeclaredField("userService");String name = userServiceField.getName();//获取set方法name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1, name.length());Method method=clazz.getMethod(name,UserService.class);//调用set方法给userService赋值UserService userService=new UserService();method.invoke(userController,userService);System.out.println(userController.getUserService());}
}
运行输出:
com.bobo.UserService@610455d6
2、annotion方式注入
定义MyAutoWired注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAutoWired {
}
UserService.java
public class UserService {
}
UserController.java
public class UserController {@MyAutoWiredprivate UserService userService;public UserService getUserService() {return userService;}
}
测试类
public class MyTest {public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {UserController userController = new UserController();Class clazz = userController.getClass();//遍历UserController成员变量for (Field field : clazz.getDeclaredFields()) {//筛选出使用MyAutoWired注解的变量MyAutoWired annotation = field.getAnnotation(MyAutoWired.class);if (annotation != null) {//获取变量类型,并创建变量对象Class<?> type = field.getType();Object o = type.getConstructor().newInstance();//给使用MyAutoWired注解的变量赋值field.setAccessible(true);field.set(userController, o);System.out.println(userController.getUserService());}}}
}
运行输出:
com.bobo.UserService@3cd1a2f1
Spring IOC设计原理
这篇关于Spring框架十一、Spring IOC源码概述的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!