基于依赖注入实现原理的简单实现
spring @Autowired底层实现原理
spring 的ioc实例化是通过beanFactory+反射 实现的,下面的demo是一个简单实现,并不全面,但有助于读者对源码的阅读
注入注解Autowired和Resource 的区别
spring的 @Autowired 是先按照类型匹配,找不到就按照名称匹配
而@Resource是基于jdk的使用范围不局限于spring,跟spring匹配顺序正好相反。
注解@Autowired注入简单实现demo
public class TestAutowireImpl {
@Test
public void test(){
UserController userController=new UserController();
Class clazz=userController.getClass();
Stream.of(clazz.getDeclaredFields()).forEach(field -> {
Annotation annnotation= field.getAnnotation(Autowired2.class);
if(null!=annnotation){
field.setAccessible(true);
try {
Object o= field.getType().newInstance();
field.set(userController,o);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
}
}
定义注解
package com.springdemo.annotation.impldemo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Autowired2 {
}