目录
基础结构说明
涉及到的功能
执行流程
spring包
引导类
bean定义
注解
回调接口拓展
测试入口
service包
回调接口拓展实现
实体类
自定义注解
基础结构说明
-
spring子包内,放置spring源码相关类,如注解定义,引导类执行逻辑等
-
service子包,放置测试类,用于测试spring相关功能,如实体类、自主实现的后处理拓展等
涉及到的功能
-
componentscan扫描包
-
component bean注入
-
Scope bean作用域
-
beanDefintion bean定义对象
-
beanDefintionMap bean定义对象集合
-
getBean 获取容器bean
-
createBean 创建容器bean
-
autowird 依赖注入
-
BeanNameAware 初始化阶段回调拓展
-
initializingBean 初始化后回调拓展
-
beanPostProcess bean后置处理器拓展
-
AOP
-
vaulue注入
-
执行流程
引导类构造器(启动入口)
-
scan扫描(装配BDMap)
-
获取引导配置类的扫描注解的路径
-
解析处理路径获取类路径下的所有类资源
-
遍历所有类
-
处理类的相对路径,通过类加载器获取类的class对象
-
处理component注解获取beanname
-
扫描当前类如果实现了bean后置处理器则加入list
-
-
处理scope注解默认单例
-
组装beandeftion对象,组装beanDefinitionMap
-
-
-
遍历bdMap创建单例对象 多例直接获取的时候创建
-
createBean创建bean,使用反射获取无参构造器获取对象
-
aware拓展BeanNameAware拓展 bean初始化的阶段生效
-
BeanPostProcessor拓展,before处理
-
InitializingBean初始化后拓展
-
BeanPostProcessor拓展,after处理
-
-
创建好的bean加入单例池
spring包
引导类
package com.spring;import com.butch.AppConfig;import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;//相当于引导类
public class ButchSpringApplicationContext {private Class configClass;private Map<String, BeanDefinition> beanDefinitionMap = new HashMap();//单例池private Map<String, Object> singletonObjects = new HashMap();private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();//构造器进入spring的启动流程public ButchSpringApplicationContext(Class configClass){this.configClass = configClass;//开启扫描包scan(configClass);//遍历bdMap 创建单例对象 多例直接获取的时候创建for (Map.Entry<String,BeanDefinition> map : beanDefinitionMap.entrySet()) {String beanName = map.getKey();BeanDefinition beanDefinition = map.getValue();if ("singleton".equals(beanDefinition.getScope())){Object bean = createBean(beanName, beanDefinition);singletonObjects.put(beanName,bean);}}}//创建Beanprivate Object createBean(String beanName, BeanDefinition beanDefinition) {//使用反射Class type = beanDefinition.getType();Object instance = null;try {instance = type.getConstructor().newInstance();//处理依赖注入Field[] declaredFields = type.getDeclaredFields();//遍历该类所有属性 是否加了依赖注入注解for (Field declaredField : declaredFields) {if (declaredField.isAnnotationPresent(Autowired.class)){//进行依赖注入declaredField.setAccessible(true);declaredField.set(instance,getBean(declaredField.getName()));}}//BeanNameAware拓展 bean初始化的阶段生效if (instance instanceof BeanNameAware){((BeanNameAware) instance).setBeanName(beanName);}//后置处理器前扩展for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {beanPostProcessor.postProcessBeforeInitialization(instance,beanName);}if (instance instanceof InitializingBean){((InitializingBean) instance).afterPropertiesSet();}//后置处理器后扩展for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {instance = beanPostProcessor.postProcessAfterInitialization(instance,beanName);}} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();}return instance;}//getbean方法public Object getBean(String beanName){//主要根据BDMap判断获取if (!beanDefinitionMap.containsKey(beanName)){throw new NullPointerException();}BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);//区分单例多例if ("singleton".equals(beanDefinition.getScope())){//单例直接从单例池获取Object singletonBean = singletonObjects.get(beanName);if (singletonBean == null){singletonBean = createBean(beanName,beanDefinition);singletonObjects.put(beanName,singletonBean);}return singletonBean;}else {//多例直接创建return createBean(beanName, beanDefinition);}}private void scan(Class configClass){//获取配置类的注解if (configClass.isAnnotationPresent(ComponentScan.class)){ComponentScan componentScan = (ComponentScan) configClass.getAnnotation(ComponentScan.class);//处理注解的value路径String path = componentScan.value();path = path.replaceAll("\\.","/");System.out.println("path = " + path);//获取应用类加载器ClassLoader classLoader = ButchSpringApplicationContext.class.getClassLoader();//获取路径下的资源URL resource = classLoader.getResource(path);//处理资源文件File file = new File(resource.getFile());if (file.isDirectory()){for (File o : file.listFiles()) {String absolutePath = o.getAbsolutePath();//处理类路径 absolutePath = com.butch.serivce.UserServiceabsolutePath = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));absolutePath = absolutePath.replace("\\", ".");System.out.println("absolutePath = " + absolutePath);//开始装配有component注解的对象try {//通过应用类加载器获取类的class对象Class<?> aClass = classLoader.loadClass(absolutePath);if (aClass.isAnnotationPresent(Component.class)) {//加入自主实现的后置处理器if (BeanPostProcessor.class.isAssignableFrom(aClass)){BeanPostProcessor beanPostProcessor = (BeanPostProcessor) aClass.getConstructor().newInstance();beanPostProcessorList.add(beanPostProcessor);}Component annotation = aClass.getAnnotation(Component.class);//获取beannameString beanName = annotation.value();if ("".equals(beanName)) {//jdk提供的默认beanNamebeanName = Introspector.decapitalize(aClass.getSimpleName());}BeanDefinition beanDefinition = new BeanDefinition();beanDefinition.setType(aClass);//处理bean是否单例if (aClass.isAnnotationPresent(Scope.class)) {Scope scope = aClass.getAnnotation(Scope.class);String value = scope.value();beanDefinition.setScope(value);} else {//默认单例beanDefinition.setScope("singleton");}//放入bean定义mapbeanDefinitionMap.put(beanName, beanDefinition);}}catch (Exception e){e.printStackTrace();}}}}}}
bean定义
package com.spring;/*** bean定义对象 存放一些bean的公共属性*/
public class BeanDefinition {private Class type;private String scope;private boolean isLazy;public Class getType() {return type;}public void setType(Class type) {this.type = type;}public String getScope() {return scope;}public void setScope(String scope) {this.scope = scope;}public boolean isLazy() {return isLazy;}public void setLazy(boolean lazy) {isLazy = lazy;}
}
注解
package com.spring;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 Autowired {}
package com.spring;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {String value() default "";}
package com.spring;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ComponentScan {String value() default "";}
package com.spring;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Scope {String value() default "";}
回调接口拓展
package com.spring;public interface BeanNameAware {void setBeanName(String name);
}
package com.spring;//bean后置处理器
public interface BeanPostProcessor {default Object postProcessBeforeInitialization(Object bean, String beanName) {return bean;}default Object postProcessAfterInitialization(Object bean, String beanName) {return bean;}
}
package com.spring;//初始化后
public interface InitializingBean {void afterPropertiesSet();
}
测试入口
package com.butch;import com.butch.serivce.UserInterface;
import com.spring.ButchSpringApplicationContext;public class TestSpring {public static void main(String[] args) {//开启扫描配置类 -> 创建单例beanButchSpringApplicationContext butchSpringApplication = new ButchSpringApplicationContext(AppConfig.class);UserInterface userService = (UserInterface) butchSpringApplication.getBean("userService");userService.test();}
}
package com.butch;import com.spring.ComponentScan;@ComponentScan("com.butch.serivce")
public class AppConfig {}
service包
回调接口拓展实现
package com.butch.serivce;public interface UserInterface {public void test();
}
package com.butch.serivce;import com.spring.BeanPostProcessor;
import com.spring.Component;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;//使用jdk代理实现一个aop
@Component
public class ButchBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) {if ("userService".equals(beanName)){Object proxyInstance = Proxy.newProxyInstance(ButchBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("==========beanPostProcessAop================");Object invoke = method.invoke(bean, args);return invoke;}});return proxyInstance;}return bean;}
}
package com.butch.serivce;import com.spring.BeanPostProcessor;
import com.spring.Component;import java.lang.reflect.Field;//注入后置处理
@Component
public class ButchValueBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) {for (Field field : bean.getClass().getDeclaredFields()) {//查看bean属性是否有value注解if (field.isAnnotationPresent(ButchValue.class)){//注入值field.setAccessible(true);try {field.set(bean,field.getAnnotation(ButchValue.class).value());} catch (IllegalAccessException e) {e.printStackTrace();}}}return bean;}
}
实体类
package com.butch.serivce;import com.spring.*;/***/
@Component
@Scope
public class UserService implements BeanNameAware,UserInterface,InitializingBean{@Overridepublic void afterPropertiesSet() {System.out.println("==========InitializingBean==========初始化后处理");}@Autowiredprivate OrderService orderService;@ButchValue("butch")private String name;public void test() {System.out.println("===============orderService============" + orderService + "=============" + name);}public void setBeanName(String name) {System.out.println("============BeanNameAwar==========" + name);}
}
package com.butch.serivce;import com.spring.Component;/***/@Component
public class OrderService {public void test() {System.out.println("test");}
}
自定义注解
package com.butch.serivce;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 ButchValue {String value() default "";
}