spring依赖注入简单实现

spring @Autowired底层实现原理

spring 的ioc实例化是通过beanFactory+反射 实现的,下面的demo是一个简单实现,并不全面,但有助于读者对源码的阅读

注入注解Autowired和Resource 的区别
spring的 @Autowired 是先按照类型匹配,找不到就按照名称匹配
而@Resource是基于jdk的使用范围不局限于spring,跟spring匹配顺序正好相反。

注解@Autowired注入简单实现demo

public class TestAutowireImpl {
    @Test
    public void test(){
        UserController userController=new UserController();
        Class clazz=userController.getClass();
        Stream.of(clazz.getDeclaredFields()).forEach(field -> {
            Annotation annnotation= field.getAnnotation(Autowired2.class);
            if(null!=annnotation){
                field.setAccessible(true);
                try {
                   Object o= field.getType().newInstance();

                   field.set(userController,o);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}

定义注解

package com.springdemo.annotation.impldemo;

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Autowired2 {

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值