基于注解方式的 自定义IOC容器 核心代码块

自定义@Service、@Autowired、@Transactional注解类,完成基于注解的IOC容器(Bean对象创建及依赖注入维护)和声明式事务控制
注意考虑以下情况:
1)注解有无value属性值【@service(value=""@Repository(value="")】

2)service层是否实现接口的情况【jdk还是cglib】

BeanFactory

完成对注解的 解析, Bean对象创建及依赖注入维护

package com.lwl.edu.factory;

import com.lwl.edu.annotation.Autowired;
import com.lwl.edu.annotation.Repository;
import com.lwl.edu.annotation.Service;
import com.lwl.edu.annotation.Transactional;
import com.lwl.edu.utils.ClassUtil;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class BeanFactory {
    // 存储对象
    //存放注解对象的容器
    private static ConcurrentHashMap<String,Object>  beans =new ConcurrentHashMap<String,Object>();;

    //包路径


    //存放beans
    private static List<Class<?>> classes;

    static {
        Properties properties = readPropertiesFile();
        final String BASE_PACKAGE = properties.getProperty("base-package");
        //扫描表 加载指定类
        classes = ClassUtil.getClasses(BASE_PACKAGE);

        if(classes.size()> 0){

            //第一步 获取 @Service  注解类  并将其实例化
            for (Class<?> clazz:classes){
                Service annotation =clazz.getDeclaredAnnotation(Service.class);
                if(annotation !=null){
                    String beanId  =annotation.value();

                    if (beanId.trim().equals("") ){
                        String className = clazz.getInterfaces()[0].getSimpleName();
                         beanId = toLowerCaseFirstOne(className);
                    }

                    Object bean = null;
                    try {
                        bean = clazz.newInstance();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    beans.put(beanId,bean);
                }
            }


            //第一步 获取 @Repository  注解类  并将其实例化
            for (Class<?> clazz:classes){
                Repository annotation =clazz.getDeclaredAnnotation(Repository.class);
                if(annotation !=null){
                    String beanId  =annotation.value();
                   if(beanId.trim().equals("")) {
                        String className = clazz.getSimpleName();
                        beanId = toLowerCaseFirstOne(className);
                    }
                    Object bean = null;
                    try {
                        bean = clazz.newInstance();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    beans.put(beanId,bean);
                }
            }



            /**
             * @Autowired
             */
            //遍历所有的注解对象
            Set<Map.Entry<String, Object>> entrySet = beans.entrySet();
            for (Map.Entry<String, Object> entry:entrySet){
                //获取注解对象,判断是否有属性的依赖注入
                Object value = entry.getValue();
                try {
                    //使用反射机制获取当前类的所有属性
                    Class<? extends Object> class1 = value.getClass();
                    Field[] fields =  class1.getDeclaredFields();
                    for (Field field:fields){
                        Autowired autowired = field.getDeclaredAnnotation(Autowired.class);
                        if(autowired !=null){
                            //获取属性名称
                            String name =autowired.value();
                            if (name.trim().equals("")){
                                String className = field.getName();
                                name = toLowerCaseFirstOne(className);
                            }
                            Object bean =getBean(name);
                            field.setAccessible(true);
                            //给属性赋值
                            field.set(value,bean);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            /**
             * @Transactional
             */
            for (Class<?> clazz:classes){
                Transactional transactional =clazz.getDeclaredAnnotation(Transactional.class);
                if(transactional !=null){
                    Service serviceAnnotation =clazz.getDeclaredAnnotation(Service.class);
                    //获取原对象
                    String beanId  =serviceAnnotation.value();
                    if (beanId.trim().equals("") ){
                        String className = clazz.getInterfaces()[0].getSimpleName();
                        beanId = toLowerCaseFirstOne(className);
                    }
                    Object oBean = beans.get(beanId);//被代理对象
                    //转为代理对象
                    ProxyFactory proxyFactory = (ProxyFactory) beans.get("proxyFactory");
                    Object proxy = proxyFactory.getJdkProxy(oBean);//代理对象
                    //代理对象替换原对象
                    beans.put(beanId,proxy);
                }

            }
        }


    }
    public static Object getBean(String beanId) {

        //从bean对象池map中获取
        Object bean = beans.get(beanId);
        return bean;
    }

    //首字母转小写
    public static String toLowerCaseFirstOne(String s){
        if(Character.isLowerCase(s.charAt(0))){
            return s;
        }else{
            return (new StringBuffer()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
        }
    }


    private static Properties readPropertiesFile() {
        Properties pros = new Properties();
        try {
            InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("application.properties");
            pros.load(new InputStreamReader(resourceAsStream, "UTF-8"));
            return pros;
        } catch (Exception e) {
            System.err.println("读取失败");
            e.printStackTrace();
        }
        return null;
    }

}

ProxyFactory

代理对象工厂:生成代理对象的

Jdk动态代理

 /**
     * Jdk动态代理
     * @param obj  委托对象
     * @return   代理对象
     */
    public Object getJdkProxy(Object obj) {

        // 获取代理对象
        return  Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result = null;

                        try{
                            // 开启事务(关闭事务的自动提交)
                            transactionManager.beginTransaction();

                            result = method.invoke(obj,args);

                            // 提交事务

                            transactionManager.commit();
                        }catch (Exception e) {
                            e.printStackTrace();
                            // 回滚事务
                            transactionManager.rollback();

                            // 抛出异常便于上层servlet捕获
                            throw e;

                        }

                        return result;
                    }
                });

    }

使用cglib动态代理生成代理对象

/**
     * 使用cglib动态代理生成代理对象
     * @param obj 委托对象
     * @return
     */
    public Object getCglibProxy(Object obj) {
        return  Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                try{
                    // 开启事务(关闭事务的自动提交)
                    transactionManager.beginTransaction();

                    result = method.invoke(obj,objects);

                    // 提交事务

                    transactionManager.commit();
                }catch (Exception e) {
                    e.printStackTrace();
                    // 回滚事务
                    transactionManager.rollback();

                    // 抛出异常便于上层servlet捕获
                    throw e;

                }
                return result;
            }
        });
    }

TransactionManager

事务管理器类:负责手动事务的开启、提交、回滚

package com.lwl.edu.utils;

import com.lwl.edu.annotation.Autowired;
import com.lwl.edu.annotation.Repository;

import java.sql.SQLException;

/**
 * 事务管理器类:负责手动事务的开启、提交、回滚
 */

@Repository(value = "transactionManager")
public class TransactionManager {

    @Autowired(value = "connectionUtils")
    private ConnectionUtils connectionUtils;

    // 开启手动事务控制
    public void beginTransaction() throws SQLException {
        connectionUtils.getCurrentThreadConn().setAutoCommit(false);
    }


    // 提交事务
    public void commit() throws SQLException {
        connectionUtils.getCurrentThreadConn().commit();
    }


    // 回滚事务
    public void rollback() throws SQLException {
        connectionUtils.getCurrentThreadConn().rollback();
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

时小浅

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

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

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

打赏作者

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

抵扣说明:

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

余额充值