包结构图:spring包下代表的是模拟spring的源码
?定义@CompontentScan,@Compontent,@Autowired,@Scope
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.TYPE)
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;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
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;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Autowired {
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;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Scope {
String value() default "";
}
模拟Spring容器(包含加载bean,创建bean,获取bean) ?
package com.spring;
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;
//模拟spring容器
public class ShenApplicationContext {
private Class configClass;
Map<String,BeanDefinition> beanDefinitionMap=new HashMap<>();
//创建单例池
Map<String,Object> singletonObjects=new HashMap<>();
List<BeanPostProcessor> beanPostProcessorList=new ArrayList<>();
public ShenApplicationContext(Class configClass) {
this.configClass = configClass;
//扫描
scan(configClass);
for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
String beanName = entry.getKey();
BeanDefinition beanDefinition = entry.getValue();
if (beanDefinition.getScope().equals("singleton")) {
Object bean = createBean(beanName, beanDefinition);
//如果是单例则存入单例池
singletonObjects.put(beanName, bean);
}
}
}
private Object createBean(String beanName,BeanDefinition beanDefinition){
Class clazz = beanDefinition.getType();
Object instance=null;
try {
//通过构造方法实例化 ps:这里只实现了无参的方式
instance = clazz.getConstructor().newInstance();
for (Field field : clazz.getDeclaredFields()) {
if (field.isAnnotationPresent(Autowired.class)) {
field.setAccessible(true);
field.set(instance, getBean(field.getName()));
}
}
//获取bean的名字
if (instance instanceof BeanNameAware) {
((BeanNameAware)instance).setBeanName(beanName);
}
//初始化前过程
for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
instance= beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
}
//初始化过程
if(instance instanceof InitializingBean){
((InitializingBean)instance).afterPropertiesSet();
}
//初始化后过程(模拟AOP过程)
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;
}
public Object getBean(String beanName){
if (!beanDefinitionMap.containsKey(beanName)) {
throw new NullPointerException();
}
BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
if (beanDefinition.getScope().equals("singleton")) {
//单例 从单例池中取出
Object singletonBean = singletonObjects.get(beanName);
//若在单例池中拿不到bean则去创建
if(null==singletonBean){
singletonBean= createBean(beanName, beanDefinition);
singletonObjects.put(beanName, singletonBean);
}
return singletonBean;
}else {
//多例 直接创建Bean
Object prototypeBean = createBean(beanName, beanDefinition);
return prototypeBean;
}
}
private void scan(Class configClass) {
if (configClass.isAnnotationPresent(ComponentScan.class)) {
//获取包路径
ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
String path = componentScanAnnotation.value();
// System.out.println(path);
path=path.replace(".", "/");
//获取类加载器 通过类加载器获取到 .class文件目录
ClassLoader classLoader = ShenApplicationContext.class.getClassLoader();
URL resource = classLoader.getResource(path);
File file=new File(resource.getFile());
if (file.isDirectory()) {
for (File f : file.listFiles()) {
//获取Bean的class文件路径
String absolutePath = f.getAbsolutePath();
absolutePath = absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class"));
absolutePath = absolutePath.replace("\\", ".");
try {
Class<?> clazz = classLoader.loadClass(absolutePath);
if (clazz.isAnnotationPresent(Component.class)) {
if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
BeanPostProcessor instance = (BeanPostProcessor) clazz.getConstructor().newInstance();
beanPostProcessorList.add(instance);
}
String beanName = clazz.getAnnotation(Component.class).value();
if("".equals(beanName)){
//spring底层生成默认BeanName的方法
beanName= Introspector.decapitalize(clazz.getSimpleName());
}
//如果有Component注解代表这是一个Bean
BeanDefinition beanDefinition=new BeanDefinition();
beanDefinition.setType(clazz);
if (clazz.isAnnotationPresent(Scope.class)) {
Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
String value = scopeAnnotation.value();
//可能是单例也可能是多例(原型)
beanDefinition.setScope(value);
}else {
//单例
beanDefinition.setScope("singleton");
}
beanDefinitionMap.put(beanName,beanDefinition);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
}
=====================================================================================
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;
//spring底层实现初始化的接口
public interface InitializingBean {
void afterPropertiesSet();
}
===================================================================================
package com.spring;
//spring底层实现初始化前和初始化后接口
public interface BeanPostProcessor {
default Object postProcessBeforeInitialization(Object bean, String beanName) {
return bean;
}
default Object postProcessAfterInitialization(Object bean, String beanName) {
return bean;
}
}
===================================================================================
package com.spring;
//可以通过这个接口获得bean的名字
public interface BeanNameAware {
void setBeanName(String name);
}
业务代码: ?
package com.tian;
import com.spring.ShenApplicationContext;
import com.tian.service.UserServiceInterface;
/**
* 模拟spring创建Bean的过程
*/
public class Test {
public static void main(String[] args) {
ShenApplicationContext shenApplicationContext=new ShenApplicationContext(AppConfig.class);
UserServiceInterface userService = (UserServiceInterface) shenApplicationContext.getBean("userService");
userService.test();
}
}
=======================================================================================
package com.tian;
import com.spring.ComponentScan;
@ComponentScan("com.tian.service")
public class AppConfig {
}
=======================================================================================
package com.tian.service;
import com.spring.Autowired;
import com.spring.BeanNameAware;
import com.spring.Component;
import com.spring.Scope;
@Component("userService")
@Scope("singleton")
public class UserService implements UserServiceInterface , BeanNameAware {
@Autowired
private OrderService orderService;
@ShenValue("xxxxx")
private String test;
@Override
public void test(){
System.out.println(test);
System.out.println("test");
}
@Override
public void setBeanName(String name) {
System.out.println("bean的名字"+name);
}
}
=========================================================================================
package com.tian.service;
public interface UserServiceInterface {
void test();
}
=======================================================================================
package com.tian.service;
import com.spring.Component;
@Component
public class OrderService {
}
========================================================================================
package com.tian.service;
import com.spring.BeanPostProcessor;
import com.spring.Component;
import java.lang.reflect.Field;
//初始化前操作
@Component
public class ShenBeanValuePostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
for (Field field : bean.getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(ShenValue.class)) {
field.setAccessible(true);
try {
field.set(bean,field.getAnnotation(ShenValue.class).value());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return bean;
}
}
========================================================================================
package com.tian.service;
import com.spring.BeanPostProcessor;
import com.spring.Component;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//初始化后操作
@Component
public class ShenBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if(beanName.equals("userService")){
Object proxyInstance = Proxy.newProxyInstance(ShenBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("切面逻辑");
return method.invoke(bean, args);
}
});
return proxyInstance;
}
return bean;
}
}
===================================================================================
package com.tian.service;
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 ShenValue {
String value() default "";
}
运行结果:
?
|