Spring的一大作用就是IOC,让使用者在使用对象的时候不用手动去赋值属性对象,等于说是把控制权从用户交给了spring,所以叫做IOC(Inversion of Control)
- 自定义一个注解
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Autoload { }
- 定义一个bean对象,其中有一个属性是另外一个对象
public class TestinjectBean { @Autoload public Car car; } public class Car { public void run(){ System.out.println("豪华跑车正在行驶……"); } }
- 定义一个beanfactory,可以根据class获取到bean对象,并且给加了注解的字段自动赋值
public class BeanFactory { /** * 根据完整的类名返回bean对象 * */ public Object getBeanByClass(Class clazz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Object obj = null; Constructor constructor = clazz.getDeclaredConstructor(null); obj = constructor.newInstance(); Field[] fields = clazz.getDeclaredFields(); for(Field field :fields){ Annotation[] annotations = field.getAnnotations(); for(Annotation annotation : annotations){ if(annotation.annotationType().getName().equals("com.chaoxing.springtest.annotation.Autoload")) { if (!field.getType().isPrimitive()) { Class fieldClazz = field.getType(); field.set(obj, fieldClazz.newInstance()); } } } } return obj; } }
示例
public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException { BeanFactory factory = new BeanFactory(); Class clazz = Class.forName("com.chaoxing.springtest.bean.TestinjectBean"); TestinjectBean bean = (TestinjectBean) factory.getBeanByClass(clazz); bean.car.run(); }
整个代码流程为实现最简单的依赖注入流程,不考虑任何异常,旨在加深理解spring IOC的基本思路