@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();
}
}
}
测试结果