自定义实现一个Bean容器

使用自定义注解实现了一个简单的支持包扫描的bean容器

加入依赖

    
      org.reflections
      reflections
      0.9.11
    

自定义一个注解

import java.lang.annotation.*;

/**
 * @author fei
 * @version V1.0
 * @date 2019/06/08 12:41
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Service {
    String value();
}

定义类并添加刚新建的注解

/**
 * @author fei
 * @version V1.0
 * @date 2019/06/08 12:41
 */
@Service("test1")
public class TestService1 {

    public void index() {
        System.out.println("Hello World TestService1");
    }
}

/**
 * @author fei
 * @version V1.0
 * @date 2019/06/08 12:45
 */
@Service(value = "test3")
public class TestService3 {

    public void index() {
        System.out.println("Hello World TestService3");
    }
}

新建bean工厂类对包进行扫描并处理

import org.reflections.Reflections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author fei
 * @version V1.0
 * @date 2019/06/08 12:42
 */
public class BeanFactory {
    /**
     * Bean对象容器
     */
    private static final Map BEAN_CONTAINER = new HashMap<>();

    /**
     * 对容器初始化
     * @param packageName
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static void init(String packageName) throws IllegalAccessException, InstantiationException {

        if (packageName == null || packageName.isEmpty()) {
            packageName = "com.study";
        }

        Reflections reflection = new Reflections(packageName);

        // 获得此路径下所有带有自定义Service注解的类
        Set> typesAnnotatedWith = reflection.getTypesAnnotatedWith(Service.class);

        // 将这些类通过反射 新建对象并保存到beanContainer
        for (Class aClass : typesAnnotatedWith) {
            Object bean = aClass.newInstance();
            Service annotation = aClass.getAnnotation(Service.class);
            BEAN_CONTAINER.put(annotation.value(), bean);
        }
    }
    
    /**
     * 根据注解名获取对象
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return BEAN_CONTAINER.get(beanName);
    }
}

定义一个主类

/**
 * @author fei
 * @version V1.0
 * @date 2019/06/08 12:54
 */
public class Main {

    public static void main(String[] args) {
        try {
            BeanFactory.init(null);

            TestService1 test1 = (TestService1) BeanFactory.getBean("test1");
            test1.index();

            TestService3 test3 = (TestService3) BeanFactory.getBean("test3");
            test3.index();
            
        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
    }
}

启动后就能拿到我们的bean并执行相应的方法

输出如下:

Hello World TestService1
Hello World TestService3

github代码库地址:https://github.com/sethufeifei/customizeBeanContainer

你可能感兴趣的:(自定义实现一个Bean容器)