手写spring时的一些工具类

一、注解操作的工具类,可以判断组合注解中是否包含某个注解

package syx.mvc.util;
import javax.annotation.*;
import java.lang.annotation.*;

public class AnnotationUtil {

    /**
     * 判断类上是否存在某个注解
     * @param clazz
     * @param ann
     * @return
     */
    public static boolean checkAnnotation(Class<?> clazz,Class<?> ann){
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation.annotationType() != Deprecated.class &&
                    annotation.annotationType() != SuppressWarnings.class &&
                    annotation.annotationType() != Override.class &&
                    annotation.annotationType() != PostConstruct.class &&
                    annotation.annotationType() != PreDestroy.class &&
                    annotation.annotationType() != Resource.class &&
                    annotation.annotationType() != Resources.class &&
                    annotation.annotationType() != Generated.class &&
                    annotation.annotationType() != Target.class &&
                    annotation.annotationType() != Retention.class &&
                    annotation.annotationType() != Documented.class &&
                    annotation.annotationType() != Inherited.class
            ) {
                if (annotation.annotationType() == ann){
                    return true;
                }else{
                    return checkAnnotation(annotation.annotationType(),ann);
                }
            }
        }
        return false;
    }
}

二、填充IOC容器的工具类

package syx.mvc.util;

import syx.mvc.annotation.Component;
import syx.mvc.annotation.Scope;
import syx.mvc.config.BeanDefinition;

import java.util.HashMap;
import java.util.List;

/**
 * 填充IOC容器
 */
public class IOCMapUtil {

    /**
     * 将扫描得到的类,根据注解添加到ioc容器
     * @param classNames
     * @param ioc
     * @return
     */
    public static HashMap<String, BeanDefinition> IOCMap(List<String> classNames, HashMap<String, BeanDefinition> ioc) {
        //检查类上的注解
        classNames.forEach(e->{
            try {
                Class<?> clazz = AnnotationUtil.class.getClassLoader().loadClass(e);
                //判断类上是否包含component注解
                boolean b = AnnotationUtil.checkAnnotation(clazz, Component.class);
                if(b){
                    Component component = clazz.getAnnotation(Component.class);
                    BeanDefinition beanDefinition = generateBeanDefinition(clazz,component,e);
                    ioc.put(beanDefinition.getBeanName(),beanDefinition);
                }
            } catch (ClassNotFoundException exception) {
                exception.printStackTrace();
            }
        });

        return ioc;
    }

    /**
     * 生成bean的定义信息
     * @param component
     * @return
     */
    private static BeanDefinition generateBeanDefinition(Class<?> clazz,Component component,String className){
        String beanName;
        String scopeType;
        BeanDefinition beanDefinition = new BeanDefinition();
        if(component == null){//如果component为null,则默认为单例,beanName为类名首字母小写
            String[] split = className.split("\\.");
            beanName = split[split.length-1];
            scopeType = "singleton";
        }else{
            if(component.value().isEmpty()){
                String[] split = className.split("\\.");
                beanName = split[split.length-1];
            }else{
                beanName = component.value();
            }
            Scope scope = clazz.getAnnotation(Scope.class);
            if(scope != null){
                scopeType = scope.value();
            }else{
                scopeType = "singleton";
            }
        }
        beanDefinition.setBeanName(beanName);
        beanDefinition.setBeanClass(clazz);
        beanDefinition.setScope(scopeType);
        return beanDefinition;
    }


}

三、根据包名,加载该包下所有class文件的工具类

package syx.mvc.util;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class LoadFileUtil {
    /**
     * 加载扫描包名下的所有class文件,返回全限定类名,例如:syx.web.controller.UserController
     * @param packageName
     * @return
     */
    public static List<String> loadFiles(String packageName) {
        if(packageName == null || packageName.isEmpty()){
            throw new RuntimeException("包名不能为空");
        }
        String path = packageName.replaceAll("\\.", "/");
        ClassLoader classLoader = LoadFileUtil.class.getClassLoader();
        URL resource = classLoader.getResource(path);
        File file = new File(resource.getFile());
        return  DFSLoadFile(file,"syx",".class");
    }


    /**
     * 深度优先搜索,扫描包下的文件
     * @param file
     * @param prefix
     * @param suffix
     * @return
     */
    private static List<String> DFSLoadFile(File file, String prefix, String suffix) {
        List<String> classFiles = new ArrayList<>();
        Stack<File> stack = new Stack<>();
        stack.push(file);
        while (!stack.isEmpty()) {
            File f = stack.pop();
            File[] files = f.listFiles();
            for (File F : files) {
                if(F.isDirectory()){
                    stack.push(F);
                }else {
                    classFiles.add(replace(F.getAbsolutePath(),prefix,suffix));
                }
            }
        }
        return classFiles;
    }
    private static String replace(String target,String prefix,String suffix){
        target = target.substring(target.indexOf(prefix), target.indexOf(suffix)).replace("\\", ".");
        return target;
    }
}

四、加载配置文件的工具类

package syx.mvc.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesUtil {
    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    public static Properties loadPropertoes(String fileName) throws IOException {
        Properties properties = null;
        InputStream inputStream = null;

        try {
            inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
            if (inputStream == null){
                throw new FileNotFoundException(fileName + "is not found");
            }

            properties = new Properties();
            properties.load(inputStream);
        }catch (IOException e){
            logger.error("load properties failure",e);
        }finally {
            if (inputStream != null){
                inputStream.close();
            }
        }

        return properties;
    }


    /**
     * 获取 String 类型的属性值(可指定默认值)
     */
    public static String getString(Properties props, String key, String defaultValue) {
        String value = defaultValue;
        if (props.containsKey(key)) {
            value = props.getProperty(key);
        }
        return value;
    }

    /**
     * 获取 String 类型的属性值(默认值为空字符串)
     */
    public static String getString(Properties props, String key) {
        return getString(props, key, "");
    }


    /**
     * 获取 int 类型的属性值(默认值为 0)
     */
    public static int getInt(Properties props, String key) {
        return getInt(props, key, 0);
    }

    /**
     * 获取 int 类型的属性值(可指定默认值)
     */
    public static int getInt(Properties props, String key, int defaultValue) {
        int value = defaultValue;
        if (props.containsKey(key)) {
            value = Integer.parseInt(props.getProperty(key));
        }
        return value;
    }


    /**
     * 获取 boolean 类型属性(默认值为 false)
     */
    public static boolean getBoolean(Properties props, String key) {
        return getBoolean(props, key, false);
    }

    /**
     * 获取 boolean 类型属性(可指定默认值)
     */
    public static boolean getBoolean(Properties props, String key, boolean defaultValue) {
        boolean value = defaultValue;
        if (props.containsKey(key)) {
            value = Boolean.parseBoolean(props.getProperty(key));
        }
        return value;
    }
}

五、反射工具类

package syx.mvc.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 反射工具类
 */
public class ReflectionUtil {
    private static final Logger logger = LoggerFactory.getLogger(ReflectionUtil.class);

    /**
     * 反射创建对象
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T crtInstance(Class<T> clazz) {
        T instance = null;
        try {
            instance = clazz.newInstance();
        } catch (Exception e) {
            logger.error("new instance failure", e);
            e.printStackTrace();
        }
        return instance;
    }


    /**
     * 调用方法
     * @param object
     * @param method
     * @param args
     * @return
     */
    public static Object invokeMethod(Object object, Method method, Object... args) {
        Object result = null;
        try {
            method.setAccessible(true);
            result = method.invoke(object, args);
        } catch (Exception e) {
            logger.error("new instance failure", e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 设置成员变量的值
     */
    public static void setField(Object obj, Field field, Object value) {
        try {
            field.setAccessible(true); //去除私有权限
            field.set(obj, value);
        } catch (Exception e) {
            logger.error("set field failure", e);
            throw new RuntimeException(e);
        }
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值