手写自定义Spring的IOC和AOP

1、IOC和AOP的理解

IOC是控制反转,就是将实例化对象交给Spring进行管理,由Spring容器进行管理,帮忙实现实例化对象,而不需要我们手动new一个对象。
AOP是面向切面编程,就是原有方法的逻辑不变,在调用方法前或者方法后加上自己的处理逻辑,是一种纵向增强

2、自定义Spring的@service,@Autowired、@Transactional注解类

自定义自己的注解:

package com.lwq.edu.annotation;

import java.lang.annotation.*;

/**
 * 自定义Autowired注解
 * @author liuweiqi
 */
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAutowired {
    boolean value() default true;
}

package com.lwq.edu.annotation;

import java.lang.annotation.*;

/**
 * 自定义Service
 * @author liuweiqi
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyService {
    String value() default "";
}

package com.lwq.edu.annotation;

import jdk.nashorn.internal.ir.annotations.Reference;

import java.lang.annotation.*;

/**
 * 自定义Transactional
 * @author liuweiqi
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyTransactional {
    String value() default "";
}

3、通过反射和动态代理来实现自定义注解的功能

扫描项目下的包,获取自定义注解,通过反射技术来实例化对象,通过动态代理来执行具体的方法

package com.lwq.edu.factory;

import com.alibaba.druid.util.StringUtils;
import com.lwq.edu.annotation.MyAutowired;
import com.lwq.edu.annotation.MyService;
import com.lwq.edu.annotation.MyTransactional;
import net.sf.cglib.core.CollectionUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.reflections.Reflections;

import java.io.InputStream;
import java.lang.ref.Reference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author LWQ
 *
 * 工厂类,生产对象(使用反射技术)
 */
public class BeanFactory {


    /**
     *存储对象
     */
    private static Map<String,Object> map = new HashMap<>();

    static {
        try {
            //扫描包
            Reflections reflections = new Reflections("com.lwq.edu");
            //获取反射对象集合
            Set<Class<?>> classes = reflections.getTypesAnnotatedWith(MyService.class);
            for (Class<?> aClass : classes) {
                //实例化对象
                Object o = aClass.newInstance();
                MyService myService = aClass.getAnnotation(MyService.class);
                //判断自定义myService是否有自定义id
                if(StringUtils.isEmpty(myService.value())){
                    //getName获取的是全限定类名,分割去掉前面包名部分
                    String[] split = aClass.getName().split("\\.");
                    map.put(split[split.length-1],o);
                }else {
                    map.put(myService.value(),o);
                }
            }
            //实例化完成之后维护对象的依赖关系MyAutowired,检查哪些对象需要传值进入
            for(Map.Entry<String,Object> entry :map.entrySet()){
                Object obj = entry.getValue();
                Class aClass = obj.getClass();
                //获取所有的变量
                Field[] fields = aClass.getDeclaredFields();
                //遍历属性,若持有MyAutowired注解则注入
                for (Field field : fields) {
                    //判断是否是使用MyAutowired注解的参数
                    if(field.isAnnotationPresent(MyAutowired.class)){
                        String[] split = field.getType().getName().split("\\.");
                        String name = split[split.length - 1];
                        //MyAutowired注解的位置需要set方法,方便aClass.getMethods()获取
                        Method[] methods = aClass.getMethods();
                        for (Method method : methods) {
                            if(method.getName().equalsIgnoreCase("set"+name)){
                                method.invoke(obj,map.get(name));
                            }
                        }
                    }
                }
                //判断当前类是否有MyTransactional注解,若有则使用代理对象
                if(aClass.isAnnotationPresent(MyTransactional.class)){
                    //获取代理工厂
                    ProxyFactory proxyFactory = (ProxyFactory) BeanFactory.getBean("proxyFactory");
                    //获取当前类获取的所有接口
                    Class[] interfaces = aClass.getInterfaces();
                    //判断是否实现接口
                    if(interfaces != null && interfaces.length > 0){
                        //实现接口使用jdk
                        obj = proxyFactory.getJdkProxy(obj);
                    }else {
                        //没实现使用CGLIB
                        obj = proxyFactory.getCglibProxy(obj);
                    }
                }
                map.put(entry.getKey(),obj);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 对外提供获取实例对象的接口(根据id获取)
     * @param id
     * @return
     */
    public static  Object getBean(String id) {
        return map.get(id);
    }
    }

4、使用自定义注解

@MyService("transferService")
@MyTransactional
public class TransferServiceImpl implements TransferService {

    @MyAutowired
    private AccountDao accountDao;

    // 构造函数传值/set方法传值

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

5、代码源码

https://download.csdn.net/download/qq_41267285/19748767

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring是Java开发中非常流行的框架,提供了众多的功能和特性,如依赖注入、AOP等,让开发人员可以更加轻松地开发高质量的应用程序。手写Spring功能,需要了解Spring框架的核心原理和实现方式。 手写Spring功能,首先需要实现依赖注入的功能。依赖注入即将需要使用的对象的引用注入到另一个对象中,通常使用构造函数或setter方法实现。可以创建一个注入器类,通过反射机制获取类的构造函数或setter方法,并完成依赖注入。 另外,还需要实现AOP(面向切面编程)的功能。AOP是一种常见的编程思想,用于将应用程序中的关注点分离出来,例如日志、事务、安全等,以便更好地管理和维护应用程序。实现AOP,可以使用动态代理技术或字节码生成技术。在Spring中,通常使用动态代理来实现AOP。 还需要实现Spring中的IoC(控制反转)功能。IoCSpring框架的核心,用于管理应用程序中的对象。在Spring中,通常使用ApplicationContext来管理对象。可以创建一个容器类,通过读取配置文件中的信息,创建并管理对象。 最后,还需要实现Spring中的事务管理功能。在应用程序中,一些操作可能需要使用事务来保证数据的一致性和完整性。可以创建一个事务管理器类,通过AOP技术,在需要的方法中加入事务处理的代码,以实现事务管理功能。 综上所述,手写Spring功能需要了解Spring框架的各个功能模块,并熟练掌握相关的技术实现方法。虽然实现起来需要一定的工作量,但这是一个非常有挑战性和有意义的工作,可以让开发人员更好地理解Spring框架的内部工作原理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沐晨~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值