java注解和反射----自己实现一个@Autowired

前言

Spring注解@Autowired可谓是我们每天必用,那你真的了解它的底层实现吗?今天通过一个简单的实例来模拟它的实现过程。

1. 注解类

声明一个注解类一般使用我们底层的四个元注解,相关介绍可以参考:自定义注解

package test;

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

@Retention(RetentionPolicy.RUNTIME)  //表示注解的生命周期
@Target(ElementType.FIELD)   //表示该注解用在属性上
@Documented    //该注解将被包含在javaDoc中
@Inherited    //子类可以继承父类中的注解
public @interface Autowired {

}

2. 书写业务类

[1] 编写一个要被注入的类UserService.class

package test;

public class UserService {
}

[2] 编写一个使用@Autowired的业务类
(其中get方法是为了方便后面的检验)

package test;

public class UserController {
	
	@Autowired
	private UserService userService;

	public UserService getUserService() {
		return userService;
	}
	
}

3. 使用反射完成值的注入

关键点就是通过反射获取出UserController类中属性的类型,并通过反射new出该对象,最终通过set把值设置到相应的对象中。

package test;

import java.lang.reflect.Field;

public class test {

	public static void main(String[] args) throws Exception {
		UserController userController = new UserController();
		
		//1.获取相应类对象
		Class<? extends UserController>  clazz = userController.getClass();
		//2.通过反射获取所有的属性
		Field[] fields = clazz.getDeclaredFields();
		for(Field f:fields) {
			//3.获取标注了@Autowired注解的属性
			Autowired annotation = f.getAnnotation(Autowired.class);
			if(annotation!=null) {
				//4.修改属性的权限值
				f.setAccessible(true);
				Class<?> type = f.getType();  //获取出相应的类型值
				//5.new出相应类型的对象
				Object o = type.newInstance();
				//6.把值进行设置
				f.set(userController, o);
			}
		}
		System.out.println(userController.getUserService());

	}

}

运行结果:(这里表明我们通过反射把值进行了注入)
java注解和反射----自己实现一个@Autowired_第1张图片

你可能感兴趣的:(Java注解和反射)