自定义注解模拟自动注入@Autowired

@Autowired 这种注入属性的方式就是利用了java的反射知识,field.set(value,targetObject);
@Autowired 这种注入的方式是setter注入方式的一种变体

自定义注解 LZF

// 字段、枚举的常量
@Target(ElementType.FIELD)
// 注解会在class字节码文件中存在,在运行时可以通过反射获取到
@Retention(RetentionPolicy.RUNTIME)
public @interface LZF {
}

使用自定义注解

package com.xxx.feng;

import com.xxx.model.po.TestPO;
import com.xxx.model.vo.TestParamVO;
import com.xxx.service.ITestLzfService;
import com.xxx.service.ITestService;
import org.springframework.expression.spel.ast.NullLiteral;

import java.lang.reflect.Field;

public class IndexService {

    @LZF
    ITestLzfService testService;

    public void getService(){
        System.out.println(testService);
    }

    public static void main(String[] args) {
        IndexService indexService = new IndexService();

        Class<IndexService> indexServiceClass = IndexService.class;

        try {
            Field testService = indexServiceClass.getDeclaredField("testService");

            if(testService.getAnnotation(LZF.class) != null){
                //设置私有属性的访问权限 
                testService.setAccessible(true);
                testService.set(indexService, new ITestLzfService() );

            }
            indexService.getService();
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}

测试结果

参考文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值