当前位置:   article > 正文

14-@Autowired处理

14-@Autowired处理

简单的注入

准备bean

static class Bean1 {

    @Autowired
    private Bean2 bean2;

    @Autowired
    public void setBean2(Bean2 bean2) {
        this.bean2 = bean2;
    }

    @Autowired
    private Optional<Bean2> bean3;

    @Autowired
    private ObjectFactory<Bean2> bean4;

    @Autowired
    @Lazy
    private Bean2 bean5;

}


@Component("bean2")
static class Bean2 {
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

处理注入

@Configuration
public class TestAutowired {

    @SneakyThrows
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TestAutowired.class);
        DefaultListableBeanFactory beanFactory = applicationContext.getDefaultListableBeanFactory();

        // 1. 根据成员变量类型注入
        DependencyDescriptor dd1 = new DependencyDescriptor(Bean1.class.getDeclaredField("bean2"), true);
        System.out.println(beanFactory.doResolveDependency(dd1, "bean1", null, null));

        // 2. 根据方法的入参类型注入   方法名 + 参数索引
        DependencyDescriptor dd2 = new DependencyDescriptor(new MethodParameter(Bean1.class.getMethod("setBean2", Bean2.class), 0), true);
        System.out.println(beanFactory.doResolveDependency(dd2, "bean1", null, null));

        // 3. Optional成员变量注入
        DependencyDescriptor dd3 = new DependencyDescriptor(Bean1.class.getDeclaredField("bean3"), true);
        System.out.println("bean3类型:" + dd3.getDependencyType());
        if (dd3.getDependencyType() == Optional.class) {
            // 内嵌级别+1 获取真实类型
            dd3.increaseNestingLevel();
            System.out.println("内嵌级别+1后:" + dd3.getDependencyType());
            Object ret = beanFactory.doResolveDependency(dd3, "bean1", null, null);
            System.out.println(Optional.ofNullable(ret));
        }

        // 4. ObjectFactory成员变量注入
        DependencyDescriptor dd4 = new DependencyDescriptor(Bean1.class.getDeclaredField("bean4"), true);
        System.out.println("bean4类型:" + dd4.getDependencyType());
        if (dd4.getDependencyType() == ObjectFactory.class) {
            // 内嵌级别+1 获取真实类型
            dd4.increaseNestingLevel();
            System.out.println("内嵌级别+1后:" + dd4.getDependencyType());
            Object ret = beanFactory.doResolveDependency(dd4, "bean1", null, null);
            ObjectFactory objectFactory = new ObjectFactory() {
                @Override
                public Object getObject() throws BeansException {
                    return ret;
                }
            };
            System.out.println(objectFactory.getObject());
        }

        // 5. @Lazy处理
        DependencyDescriptor dd5 = new DependencyDescriptor(Bean1.class.getDeclaredField("bean5"), true);
        // 解析@Value、@Lazy
        ContextAnnotationAutowireCandidateResolver resolver = new ContextAnnotationAutowireCandidateResolver();
        resolver.setBeanFactory(beanFactory);

        Object proxy = resolver.getLazyResolutionProxyIfNecessary(dd5, "bean1");
        System.out.println(proxy);
        // 生成的对象是动态代理
        System.out.println(proxy.getClass());

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

复杂的注入

准备bean

interface Service {
}

@Component("service1")
static class Service1 implements Service {
}

@Primary
@Component("service2")
static class Service2 implements Service {
}

@Component("service3")
static class Service3 implements Service {
}

interface DAO<T> {
}

static class Student {
}

static class Teacher {
}

@Component("DAO1")
static class DAO1 implements DAO<Student> {
}

@Component("DAO2")
static class DAO2 implements DAO<Teacher> {
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

目标类

static class Target {
    @Autowired
    private Service[] serviceArr;
    @Autowired
    private List<Service> serviceList;
    @Autowired
    private ConfigurableApplicationContext applicationContext;
    @Autowired
    private DAO<Teacher> dao;  // DAO2
    @Autowired
    @Qualifier("service2")
    private Service service;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

注入-数组

@SneakyThrows
private static void testArray(DefaultListableBeanFactory beanFactory) {
    DependencyDescriptor serviceArr = new DependencyDescriptor(Target.class.getDeclaredField("serviceArr"), true);
    // 当前属性是一个数组
    //System.out.println(serviceArr.getDependencyType());
    if (serviceArr.getDependencyType().isArray()) {
        Class<?> componentType = serviceArr.getDependencyType().getComponentType();
        System.out.println("数组类的真实类型:" + componentType);
        // 根据类型从当前容器或者父级容器中获取bean名字
        String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, componentType);
        List<Object> retBeans = new ArrayList<>();
        for (String beanName : beanNames) {
            System.out.println("findBean=>" + beanName);
            // 从容器中根据beanName获取bean
            Object ret = serviceArr.resolveCandidate(beanName, componentType, beanFactory);
            retBeans.add(ret);
        }
        // 类型转换  list->数组
        Object ret = beanFactory.getTypeConverter().convertIfNecessary(retBeans, serviceArr.getDependencyType());
        System.out.println("最终注入的数组:" + ret);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

注入-list

@SneakyThrows
private static void testList(DefaultListableBeanFactory beanFactory) {
    DependencyDescriptor serviceList = new DependencyDescriptor(Target.class.getDeclaredField("serviceList"), true);
    if (serviceList.getDependencyType() == List.class) {
        Class<?> resolveType = serviceList.getResolvableType().getGeneric().resolve();
        System.out.println("list的真实类型:" + resolveType);
        String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, resolveType);
        List<Object> ret = new ArrayList<>();
        for (String beanName : beanNames) {
            Object bean = serviceList.resolveCandidate(beanName, resolveType, beanFactory);
            ret.add(bean);
        }
        System.out.println(ret);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

注入-ApplicationContext

@SneakyThrows
private static void testApplicationContext(DefaultListableBeanFactory beanFactory) {
    DependencyDescriptor applicationContext = new DependencyDescriptor(Target.class.getDeclaredField("applicationContext"), true);

    Field resolvableDependencies = DefaultListableBeanFactory.class.getDeclaredField("resolvableDependencies");
    resolvableDependencies.setAccessible(true);
    Map<Class<?>, Object> resolvableDependencyMap = (Map<Class<?>, Object>) resolvableDependencies.get(beanFactory);
    resolvableDependencyMap.forEach((k, v) -> {
        // 几个核心类没有放在一级缓存中,而是放在了resolvableDependencies成员变量中  分别是:ResourceLoader、ApplicationEventPublisher、ApplicationContext以及BeanFactory
        System.out.println("key: " + k + ", value:" + v);
    });


    for (Map.Entry<Class<?>, Object> entry : resolvableDependencyMap.entrySet()) {
        // 左边类型   =  右边类型    即 dependencyType能否复制给 Key
        if (entry.getKey().isAssignableFrom(applicationContext.getDependencyType())) {
            System.out.println("找到了applicationContext:" + entry.getValue());
            break;
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

注入-泛型

@SneakyThrows
private static void testGeneric(DefaultListableBeanFactory beanFactory) {
    DependencyDescriptor dao = new DependencyDescriptor(Target.class.getDeclaredField("dao"), true);
    Class<?> dependencyType = dao.getDependencyType();

    // @Value @Lazy 判断@Autowired所需要的类型是否与某个BeanDefinition匹配()
    ContextAnnotationAutowireCandidateResolver resolver = new ContextAnnotationAutowireCandidateResolver();
    resolver.setBeanFactory(beanFactory);

    String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, dependencyType);
    for (String beanName : beanNames) {
        System.out.println("找到beanName:" + beanName);

        BeanDefinition beanDefinition = beanFactory.getMergedBeanDefinition(beanName);
        if (resolver.isAutowireCandidate(new BeanDefinitionHolder(beanDefinition, beanName), dao)) {
            System.out.println("当前beanName:" + beanName + "匹配");
            System.out.println(dao.resolveCandidate(beanName, dependencyType, beanFactory));
        } else {
            System.out.println("当前beanName:" + beanName + "不匹配");
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

注入-@Qualifier

@SneakyThrows
private static void testQualifier(DefaultListableBeanFactory beanFactory) {
    DependencyDescriptor service = new DependencyDescriptor(Target.class.getDeclaredField("service"), true);
    Class<?> dependencyType = service.getDependencyType();

    // @Value @Lazy 判断@Autowired所需要的类型是否与某个BeanDefinition匹配(范型、@Qualifier)
    ContextAnnotationAutowireCandidateResolver resolver = new ContextAnnotationAutowireCandidateResolver();
    resolver.setBeanFactory(beanFactory);

    String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, dependencyType);
    for (String beanName : beanNames) {
        System.out.println("找到beanName:" + beanName);

        BeanDefinition beanDefinition = beanFactory.getMergedBeanDefinition(beanName);
        if (resolver.isAutowireCandidate(new BeanDefinitionHolder(beanDefinition, beanName), service)) {
            System.out.println("当前beanName:" + beanName + "匹配");
            System.out.println(service.resolveCandidate(beanName, dependencyType, beanFactory));
        } else {
            System.out.println("当前beanName:" + beanName + "不匹配");
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

目标类

static class Target2 {
    @Autowired
    private Service service;

    @Autowired
    private Service service3;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

注入-@Primary

@SneakyThrows
private static void testPrimary(DefaultListableBeanFactory beanFactory) {
    DependencyDescriptor service = new DependencyDescriptor(Target2.class.getDeclaredField("service"), true);
    Class<?> dependencyType = service.getDependencyType();

    String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, dependencyType);
    for (String beanName : beanNames) {
        System.out.println("找到beanName:" + beanName);

        BeanDefinition beanDefinition = beanFactory.getMergedBeanDefinition(beanName);
        if (beanDefinition.isPrimary()) {
            System.out.println("当前beanName:" + beanName + "匹配");
            System.out.println(service.resolveCandidate(beanName, dependencyType, beanFactory));
        } else {
            System.out.println("当前beanName:" + beanName + "不匹配");
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

注入-byName

@SneakyThrows
private static void testName(DefaultListableBeanFactory beanFactory) {
    DependencyDescriptor service3 = new DependencyDescriptor(Target2.class.getDeclaredField("service3"), true);
    Class<?> dependencyType = service3.getDependencyType();

    String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, dependencyType);
    for (String beanName : beanNames) {
        System.out.println("找到beanName:" + beanName);
        if (beanName.equals(service3.getDependencyName())) {
            System.out.println("当前beanName:" + beanName + "匹配");
            System.out.println(service3.resolveCandidate(beanName, dependencyType, beanFactory));
        } else {
            System.out.println("当前beanName:" + beanName + "不匹配");
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/511649
推荐阅读
相关标签
  

闽ICP备14008679号