接上一篇[探究spring的底层实现原理1
上一篇从理论到源码讲到了以下四点
BeanFactory
Bean的整个生命周期
Bean的属性填充
依赖注入
这节就切合上一篇,手写一个简易版spring的小demo,看看我是怎样去实现的java
<谨供参考>
1 2 3
| ClassPathXmlApplicationContext:xml配置文件方式 AH8q3dGK2f2vLZVgbRfLTjQPySe2yRaJHs:注解方式 SpringApplication:SpringBoot方式
|
模拟注解方式启动
1 2 3
| @ComponentScan("org.xiaowu.xiaowu.spring.xiaowu") public class AppConfig { }
|
- 标注@Component的类则是需要被spring管理的
1 2 3 4 5
| @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public [@interface](https: String value() default ""; }
|
1 2 3 4 5 6 7 8 9
|
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Scope { Mode value() default Mode.SINGLETON; }
|
- BeanDefinition 描述了一个 Bean 实例,实例包含属性值、构造方法参数值以及更多实现信息.这里我放了俩参数,scope和claszz
1 2 3 4 5 6 7 8 9 10
|
@Getter @Setter public class BeanDefinition { private Class clazz; private Mode scope; }
|
- 等同spring的BeanPostProcessor.在初始化bean前后使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
@Component public class BeanPostProcessorImpl implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) { if (beanName.equals("userService")){ ((UserService)bean).setName("我是小五"); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (beanName.equals("userService")) { Object proxyInstance = Proxy.newProxyInstance(BeanPostProcessorImpl.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(bean,args); } }); return proxyInstance; } return bean; } }
|
- 等同spring的InitializingBean
1 2 3 4 5 6 7 8
|
public interface InitializingBean { void afterPropertiesSet(); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
|
public class AH8q3dGK2f2vLZVgbRfLTjQPySe2yRaJHs {
private Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(16);
private Map<String, Object> singleTonMap = new ConcurrentHashMap<>(16);
private List<BeanPostProcessor> beanPostProcessors = new ArrayList<>(16);
public AH8q3dGK2f2vLZVgbRfLTjQPySe2yRaJHs(Class configClazz) throws Exception {
if (configClazz.isAnnotationPresent(ComponentScan.class)) { ComponentScan componentScan = (ComponentScan) configClazz.getDeclaredAnnotation(ComponentScan.class); String path = componentScan.value(); ClassLoader classLoader = AH8q3dGK2f2vLZVgbRfLTjQPySe2yRaJHs.class.getClassLoader(); String filePath = StrUtil.replace(path, ".", "/"); URL url = classLoader.getResource(filePath); List<String> recursiveFiles = new ArrayList<>(); RecursiveFileUtils.recursiveFiles(url.getFile(),recursiveFiles); for (String absolutePath : recursiveFiles) { String subPath = StrUtil.sub(absolutePath, absolutePath.indexOf(path), absolutePath.lastIndexOf(".class")); Class<?> aClass = classLoader.loadClass(subPath); if (aClass.isAnnotationPresent(Component.class)) { if (BeanPostProcessor.class.isAssignableFrom(aClass)){ BeanPostProcessor beanPostProcessor = (BeanPostProcessor) aClass.getDeclaredConstructor().newInstance(); beanPostProcessors.add(beanPostProcessor); } Component componentAnnotation = aClass.getDeclaredAnnotation(Component.class); String beanName = StrUtil.isEmpty(componentAnnotation.value()) ? StrUtil.lowerFirst(aClass.getSimpleName()) : componentAnnotation.value(); BeanDefinition beanDefinition = new BeanDefinition(); beanDefinition.setClazz(aClass); if (aClass.isAnnotationPresent(Scope.class)) { Scope scopeAnnotation = aClass.getDeclaredAnnotation(Scope.class); beanDefinition.setScope(scopeAnnotation.value()); } else { beanDefinition.setScope(Mode.SINGLETON); } beanDefinitionMap.put(beanName, beanDefinition); } } for (String beanName : beanDefinitionMap.keySet()) { BeanDefinition beanDefinition = beanDefinitionMap.get(beanName); if (beanDefinition.getScope() == Mode.SINGLETON) { Object bean = singleTonMap.get(beanName); if (!Optional.ofNullable(bean).isPresent()){ bean = createBean(beanName,beanDefinition); singleTonMap.put(beanName, bean); } } } } else { throw new RuntimeException("未被标注"); }
}
private Object createBean(String beanName,BeanDefinition beanDefinition) { try { Class clazz = beanDefinition.getClazz(); Object newInstance = clazz.getDeclaredConstructor().newInstance(); for (Field declaredField : clazz.getDeclaredFields()) { if (declaredField.isAnnotationPresent(Autowired.class)) { Object bean = getBean(declaredField.getName()); if (!Optional.ofNullable(bean).isPresent()){ throw new RuntimeException("getBean "+beanName+" 错误"); } declaredField.setAccessible(true); declaredField.set(newInstance, bean); } } for (BeanPostProcessor beanPostProcessor : beanPostProcessors) { beanPostProcessor.postProcessBeforeInitialization(newInstance,beanName); } if (newInstance instanceof InitializingBean){ ((InitializingBean)newInstance).afterPropertiesSet(); } for (BeanPostProcessor beanPostProcessor : beanPostProcessors) { beanPostProcessor.postProcessAfterInitialization(newInstance,beanName); } singleTonMap.put(beanName, newInstance); return newInstance; } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } return null; }
public Object getBean(String beanName) { BeanDefinition beanDefinition = beanDefinitionMap.get(beanName); if (beanDefinition != null) { if (beanDefinition.getScope() == Mode.SINGLETON) { Object bean = singleTonMap.get(beanName); return Optional.ofNullable(bean).isPresent()?bean:createBean(beanName,beanDefinition); } else { return createBean(beanName,beanDefinition); } } throw new RuntimeException("未找到当前bean对象"); } }
|
测试一下看看
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
@Component @Scope(Mode.SINGLETON) public class UserService implements InitializingBean { @Autowired private OrderService orderService; @Setter @Getter private String name; public void test(){ System.out.println(orderService); System.out.println(name); } @Override public void afterPropertiesSet() { System.out.println("执行afterPropertiesSet方法"); } }
public class XiaowuSpringApplication {
public static void main(String[] args) throws Exception {
AH8q3dGK2f2vLZVgbRfLTjQPySe2yRaJHs annotationConfigApplicationContext = new AH8q3dGK2f2vLZVgbRfLTjQPySe2yRaJHs(AppConfig.class); UserService userService = (UserService) annotationConfigApplicationContext.getBean("userService"); userService.test(); } }
执行afterPropertiesSet方法 org.xiaowu.xiaowu.spring.xiaowu.service.OrderService@5474c6c null
|
源码仓库地址: 简易版spring demo