实现Spring简易功能

在这里插入图片描述


Autowired.java

package com.cup.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.METHOD, ElementType.FIELD})
public @interface Autowired {

}

BeanDefinition.java
package com.cup.spring;

public class BeanDefinition {
    private Class clazz;
    private String Scope;

    public Class getClazz() {
        return clazz;
    }

    public void setClazz(Class clazz) {
        this.clazz = clazz;
    }

    public String getScope() {
        return Scope;
    }

    public void setScope(String scope) {
        Scope = scope;
    }
}


BeanNameAware.java
package com.cup.spring;

public interface BeanNameAware {
    void setBeanName(String name);
}

BeanPostProcessor.java
package com.cup.spring;

public interface BeanPostProcessor {
    Object postProcessBeforeInitialization(Object bean, String beanName);

    Object postProcessAfterInitialization(Object bean, String beanName);
}

Component.java
package com.cup.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 "";
}

ComponentScan.java
package com.cup.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();
}

InitializingBean.java
package com.cup.spring;

public interface InitializingBean {
    void afterPropertiesSet() throws Exception;
}

Scope.java
package com.cup.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();
}

SiheyuanApplicationContext.java
package com.cup.spring;

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.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SiheyuanApplicationContext {
    private Class configClass;

    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>(); //单例池

    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(); //

    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public SiheyuanApplicationContext(Class configClass) {
        this.configClass = configClass;

        //解析配置类
        //ComponentScan注解--->扫描路径--->扫描--->Beandefinition--->BeanDefinitionMap
        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); //单例 bean
                singletonObjects.put(beanName, bean);
            }
        }

    }

    public Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getClazz();
        try {
            Object instance = clazz.getDeclaredConstructor().newInstance();

            // 依赖注入
            for (Field declaredField : clazz.getDeclaredFields()) {
                if (declaredField.isAnnotationPresent(Autowired.class)) {
                    Object bean = getBean(declaredField.getName());
                    declaredField.setAccessible(true);
                    declaredField.set(instance, bean);
                }
            }

            // Aware回调
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware)instance).setBeanName(beanName);
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }

            // 初始化
            if (instance instanceof InitializingBean) {
                ((InitializingBean)instance).afterPropertiesSet();
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }

            // BeanPostProcessor

            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private void scan(Class configClass) {
        ComponentScan componentScanAnnotation = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        String path = componentScanAnnotation.value(); //扫描路径
        path = path.replace(".", "/");

        // 扫描
        // Bootstarp---> jre/lib
        // Ext---------> jre/ext/lib
        // App---------> classpath
        ClassLoader classLoader = SiheyuanApplicationContext.class.getClassLoader();
        URL url = classLoader.getResource(path);
        File file = new File(url.getFile());
        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            for (File f : listFiles) {
                String fileName = f.getAbsolutePath();
                if (fileName.endsWith(".class")) {
                    String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                    className = className.replace("\\", ".");
                    try {
                        Class<?> aclass = classLoader.loadClass(className);
                        if (aclass.isAnnotationPresent(Component.class)) {
                            // 表示当前这个类是一个bean
                            // 解析类,判断当前的bean是单例bean,还是prototype的bean
                            // BeanDefinition

                            if (BeanPostProcessor.class.isAssignableFrom(aclass)) {
                                BeanPostProcessor instance = (BeanPostProcessor) aclass.getDeclaredConstructor().newInstance();
                                beanPostProcessorList.add(instance);
                            }


                            Component componentAnnotation = aclass.getDeclaredAnnotation(Component.class);
                            String beanName = 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("singleton");
                            }
                            beanDefinitionMap.put(beanName, beanDefinition);

                        }
                    } catch (ClassNotFoundException | NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public Object getBean(String beanName) {
        if (beanDefinitionMap.containsKey(beanName)) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) {
                Object o = singletonObjects.get(beanName);
                return o;
            } else {
                // 创建 bean 对象
                Object bean = createBean(beanName, beanDefinition);
                return bean;
            }
        } else { // 不存在对应的 bean
            throw new NullPointerException();
        }
    }

}

OrderService.java
package com.cup.siheyuan.service;

import com.cup.spring.Component;

@Component("orderService")
//@Scope("prototype")
public class OrderService {
}

UserService.java
package com.cup.siheyuan.service;

public interface UserService {
    void test();
}

UserServiceImpl.java
package com.cup.siheyuan.service;

import com.cup.spring.*;

@Component("userService")
//@Scope("prototype")
public class UserServiceImpl implements UserService {

    @Autowired
    private OrderService orderService;

    private String beanName;

    private String name;

    public void test() {
        System.out.println(orderService);
        //System.out.println(beanName);
        System.out.println(name);
    }

    /*@Override   implements BeanPostProcessor
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化...");
    }*/

    /*@Override   implements BeanNameAware
    public void setBeanName(String name) {
        beanName = name;
    }*/

    public void setName(String name) {
        this.name = name;
    }
}

SiheyuanBeanPostProcessor.java
package com.cup.siheyuan.service;

import com.cup.spring.BeanPostProcessor;
import com.cup.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class SiheyuanBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {

        /*if (beanName.equals("userService")) {
            System.out.println("初始化前...");
            ((UserServiceImpl)bean).setName("四合院好帅!!");
        }*/
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println("初始化后...");
        if ("userService".equals(beanName)) {
            Object proxyInstance = Proxy.newProxyInstance(SiheyuanBeanPostProcessor.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;
    }
}

AppConfig.java
package com.cup.siheyuan;

import com.cup.spring.ComponentScan;

@ComponentScan("com.cup.siheyuan.service")
public class AppConfig {

}

Test.java
package com.cup.siheyuan;

import com.cup.siheyuan.service.UserService;
import com.cup.spring.SiheyuanApplicationContext;

public class Test {
    public static void main(String[] args) {
        SiheyuanApplicationContext applicationContext = new SiheyuanApplicationContext(AppConfig.class);
        UserService userService = (UserService) applicationContext.getBean("userService");
        UserService userService1 = (UserService) applicationContext.getBean("userService");
        System.out.println(userService);
        System.out.println(userService1);
        userService.test();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值