@Compenent,@Autowired,@PostConstruct自实现

简介:

本来是想为安卓开发一套可以依赖注入的标签,但是发现安卓很难找到选定包内的java或者class文件。所以只能当做学习参考了,全套代码如下
package com.guanjian.annotion;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**

  • Created by Administrator on 2018-06-11.
    */

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Autowired {
}
package com.guanjian.annotion;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**

  • Created by Administrator on 2018-06-11.
    */

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
}
package com.guanjian.annotion;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**

  • Created by Administrator on 2018-06-11.
    */

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PostConstruct {
}
package com.guanjian.util;

import com.guanjian.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**

  • 类操作工具类
  • Created by Administrator on 2018-06-11.
    */

public final class ClassUtil {

private static final Logger LOGGER = LoggerFactory.getLogger(ClassUtil.class);

/**
 * 获取类加载器
 * @return
 */
public static ClassLoader getClassLoader() {
    return Thread.currentThread().getContextClassLoader();
}

/**
 * 加载类
 * @param className
 * @param isInitialized
 * @return
 */
public static Class<?> loadClass(String className,boolean isInitialized) {
    Class<?> cls;
    try {
        cls = Class.forName(className,isInitialized,getClassLoader());
    } catch (ClassNotFoundException e) {
        LOGGER.error("load class failure",e);
        throw new RuntimeException(e);
    }
    return cls;
}

/**
 * 获取制定包名下的所有类
 * @param packageName
 * @return
 */
public static Set<Class<?>> getClassSet(String packageName) {
    Set<Class<?>> classSet = new HashSet<Class<?>>();
    try {
        Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".","/"));
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            if (url != null) {
                String protocol = url.getProtocol();
                if (protocol.equals("file")) {
                    String packagePath = url.getPath().replaceAll("%20"," ");
                    addClass(classSet,packagePath,packageName);
                }else if (protocol.equals("jar")) {
                    JarURLConnection jarURLConnection = (JarURLConnection)url.openConnection();
                    if (jarURLConnection != null) {
                        JarFile jarFile = jarURLConnection.getJarFile();
                        if (jarFile != null) {
                            Enumeration<JarEntry> jarEntries = jarFile.entries();
                            while (jarEntries.hasMoreElements()) {
                                JarEntry jarEntry = jarEntries.nextElement();
                                String jarEntryName = jarEntry.getName();
                                if (jarEntryName.endsWith(".class")) {
                                    String className = jarEntryName.substring(0,jarEntryName.lastIndexOf(".")).replaceAll("/",".");
                                    doAddClass(classSet,className);
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("get class set failure",e);
        throw new RuntimeException(e);
    }
    return classSet;
}

private static void addClass(Set<Class<?>> classSet, String packagePath, final String packageName) {
    File[] files = new File(packagePath).listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return (pathname.isFile() && pathname.getName().endsWith(".class")) || pathname.isDirectory();
        }
    });
    for (File file:files) {
        String fileName = file.getName();
        if (file.isFile()) {
            String className = fileName.substring(0,fileName.lastIndexOf("."));
            if (StringUtil.isNotEmpty(packagePath)) {
                className = packageName + "." + className;
            }
            doAddClass(classSet,className);
        }else {
            String subPackagePath = fileName;
            if (StringUtil.isNotEmpty(packagePath)) {
                subPackagePath = packagePath + "/" +subPackagePath;
            }
            String subPackageName = fileName;
            if (StringUtil.isNotEmpty(packageName)) {
                subPackageName = packageName + "." +subPackageName;
            }
            addClass(classSet,subPackagePath,subPackageName);
        }
    }
}
private static void doAddClass(Set<Class<?>> classSet,String className) {
    Class<?> cls = loadClass(className,false);
    classSet.add(cls);
}

}
package com.guanjian.util;

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

import java.lang.reflect.Field;

/**

  • 反射工具类
  • Created by Administrator on 2018-06-11.
    */

public final class ReflectionUtil {

private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);

/**
 * 创建实例
 * @param cls
 * @return
 */
public static Object newInstance(Class<?> cls) {
    Object instance;
    try {
        instance = cls.newInstance();
    } catch (Exception e) {
        LOGGER.error("new instance failure",e);
        throw new RuntimeException(e);
    }
    return instance;
}

/**
 * 设置成员变量值
 * @param obj
 * @param field
 * @param value
 */
public static void setField(Object obj, Field field,Object value) {
    try {
        field.setAccessible(true);
        field.set(obj,value);
    } catch (IllegalAccessException e) {
        LOGGER.error("set field failure",e);
        throw new RuntimeException(e);
    }
}

}
package com.guanjian.util;

import com.guanjian.annotion.Component;

import java.util.HashSet;
import java.util.Set;

/**

  • 类操作助手类
  • Created by Administrator on 2018-06-11.
    */

public final class ClassHelper {

/**
 * 定义类集合(用于存放所加载的类)
 * @param basePackage
 */
private static  Set<Class<?>> CLASS_SET;

/**
 * 扫描所有的包,获取类集合放入CLASS_SET
 * @param basePackage
 */
public static void setClassSet(String basePackage) {
    CLASS_SET = ClassUtil.getClassSet(basePackage);
}

/**
 * 获取应用包名下的所有类
 * @return
 */
public static Set<Class<?>> getClassSet() {
    return CLASS_SET;
}

/**
 * 获取应用包名下所有Comonent类
 * @return
 */
public static Set<Class<?>> getComponentClassSet() {
    Set<Class<?>> classSet = new HashSet<Class<?>>();
    for (Class<?> cls:CLASS_SET) {
        if (cls.isAnnotationPresent(Component.class)) {
            classSet.add(cls);
        }
    }
    return classSet;
}

/**
 * 获取应用包名下所有Bean类
 * @return
 */
public static Set<Class<?>> getBeanClassSet() {
    Set<Class<?>> beanClassSet = new HashSet<Class<?>>();
    beanClassSet.addAll(getComponentClassSet());
    return beanClassSet;
}

}
package com.guanjian.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**

  • Bean助手类
  • Created by Administrator on 2018-06-11.
    */

public final class BeanHelper {

/**
 * 定义Bean映射(用于存放Bean类与Bean实例的映射关系)
 */
private static final Map<Class<?>,Object> BEAN_MAP = new HashMap<Class<?>, Object>();

/**
 * 获取所有的映射关系
 */
public static void setBeanMap() {
    Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet();
    for (Class<?> beanClass:beanClassSet) {
        Object obj = ReflectionUtil.newInstance(beanClass);
        BEAN_MAP.put(beanClass,obj);
    }
}

/**
 * 获取Bean映射
 * @return
 */
public static Map<Class<?>,Object> getBeanMap() {
    return BEAN_MAP;
}

/**
 * 获取Bean实例
 * @param cls
 * @param <T>
 * @return
 */
public static <T> T getBean(Class<T> cls) {
    if (!BEAN_MAP.containsKey(cls)) {
        throw new RuntimeException("Can not get bean by class:" + cls);
    }
    return (T)BEAN_MAP.get(cls);
}

}
package com.guanjian.util;

import com.guanjian.annotion.Autowired;
import com.guanjian.annotion.PostConstruct;
import com.guanjian.utils.ArrayUtil;
import com.guanjian.utils.CollectionUtil;

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

/**

  • Created by Administrator on 2018-06-11.
    */

public final class IocHelper {

public static void ioc(){
    //获取所有的Bean类与Bean实例之间的映射关系
    Map<Class<?>,Object> beanMap = BeanHelper.getBeanMap();
    if (CollectionUtil.isNotEmpty(beanMap)) {
        //遍历Bean Map
        for (Map.Entry<Class<?>,Object> beanEntry:beanMap.entrySet()) {
            //从BeanMap中获取Bean类与Bean实例
            Class<?> beanClass = beanEntry.getKey();
            Object beanInstance = beanEntry.getValue();
            //获取Bean类定义的所有成员变量
            Field[] beanFields = beanClass.getDeclaredFields();
            if (ArrayUtil.isNotEmpty(beanFields)) {
                //遍历Bean Field
                for (Field beanField:beanFields) {
                    //判断当前Bean Field是否带有Autowired注解
                    if (beanField.isAnnotationPresent(Autowired.class)) {
                        //在Bean Map中获取Bean Field对应的实例
                        Class<?> beanFieldClass = beanField.getType();
                        Object beanFieldInstance = beanMap.get(beanFieldClass);
                        if (beanFieldInstance != null) {
                            //通过反射初始化BeanField的值
                            ReflectionUtil.setField(beanInstance,beanField,beanFieldInstance);
                        }
                    }
                }
            }
            Method[] beanMethods = beanClass.getMethods();
            if (ArrayUtil.isNotEmpty(beanMethods)) {
                //遍历method
                for (Method method:beanMethods) {
                    //判断当前注解是否有PostConstruct注解
                    if (method.isAnnotationPresent(PostConstruct.class)) {
                        try {
                            //执行该方法
                            method.invoke(beanInstance,null);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

}
package com.guanjian.manage;

import com.guanjian.util.BeanHelper;
import com.guanjian.util.ClassHelper;
import com.guanjian.util.IocHelper;

/**

  • Created by Administrator on 2018-06-11.
    */

public class Manager {

public static Object getBean(Class<?> beanClass) {
    return BeanHelper.getBean(beanClass);
}
public static void scanAndImp(String basePackage) {
    ClassHelper.setClassSet(basePackage);
    BeanHelper.setBeanMap();
    IocHelper.ioc();
}

}
测试代码

package com.guanjian.test.compent;

import com.guanjian.annotion.Component;
import com.guanjian.annotion.PostConstruct;

/**

  • Created by Administrator on 2018-06-11.
    */

@Component
public class Test1 {

private String hello;
@PostConstruct
public void init() {
    hello = "你好";
}
public void show() {
    System.out.println(hello);
}

}
package com.guanjian.test.compent;

import com.guanjian.annotion.Autowired;
import com.guanjian.annotion.Component;

/**

  • Created by Administrator on 2018-06-11.
    */

@Component
public class Test2 {

@Autowired
private Test1 test1;
public void show() {
    test1.show();
}

}
package com.guanjian.test;

import com.guanjian.manage.Manager;
import com.guanjian.test.compent.Test2;

/**

  • Created by Administrator on 2018-06-11.
    */

public class Test {

public static void main(String[] args) {
    Manager.scanAndImp("com.guanjian.test");
    Test2 test2 = (Test2)Manager.getBean(Test2.class);
    test2.show();
}

}

相关文章
|
6月前
|
Java Spring
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
`@RequiredArgsConstructor(onConstructor = @__(@Autowired))` 是一个注解,通常用于在类中生成一个包含所有`final`和`@NonNull`注解的字段的构造函数,并且对这些字段进行自动注入(使用Spring框架的`@Autowired`注解)。让我们详细解释一下: 1. **`@RequiredArgsConstructor` 注解:** - **作用:** Lombok 提供的注解,用于自动生成类的构造函数。 - **生成的构造函数:** 生成一个包含所有`final`字段的构造函数,同时也包括被`@NonNull`注解
665 1
|
4月前
|
Java Spring
ApplicationContextAware 的理解和应用
ApplicationContextAware 的理解和应用
39 2
|
3月前
ApplicationContextAware
ApplicationContextAware
13 0
|
4月前
|
Java Spring
@PostConstruct注解的使用
@PostConstruct注解的使用
103 0
|
5月前
|
Java
@RequiredArgsConstructor(onConstructor_ = @Autowired)报错
@RequiredArgsConstructor(onConstructor_ = @Autowired)报错
@RequiredArgsConstructor(onConstructor=@_(@Autowired))是什么语法?
@RequiredArgsConstructor(onConstructor=@_(@Autowired))是什么语法?
233 0
|
11月前
RequiredArgsConstructor
RequiredArgsConstructor
84 1
|
6月前
|
Java Spring
spring注解@Autowired、@Resource说明
spring注解@Autowired、@Resource说明
|
Java Spring 容器
@PostConstruct使用
@PostConstruct使用
61 0
|
开发框架 Java Spring
还在使用@Autowired 吗?并不推荐使用!
还在使用@Autowired 吗?并不推荐使用!