1. 程式人生 > 其它 >手寫實現Spring IoC Autowired

手寫實現Spring IoC Autowired

MyAutowired註解類

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 MyAutowired {

}

UserController控制器類

public class UserController {
    @MyAutowired
    private UserService userService;

    public String getUserName() {
        return userService.getUserName();
    }
}

UserService服務類

public class UserService {
    public String getUserName() {
        return "abc";
    }
}

TestMyAutowired測試類

import org.junit.Test;

import java.lang.reflect.Field;

import static org.junit.Assert.assertEquals;

public class TestMyAutowired {
    @Test
    public void test() {
        UserController userController = new UserController();

        // 獲取Class物件
        Class clazz = userController.getClass();
        // 遍歷userController的所有屬性
        for (Field field : clazz.getDeclaredFields()) {
            // 確認屬性是否有MyAutowired註解
            MyAutowired annotation = field.getAnnotation(MyAutowired.class);
            if (annotation == null) {
                continue;
            }

            // 允許訪問私有屬性
            field.setAccessible(true);
            // 獲取屬性的型別
            Class type = field.getType();
            try {
                // 建立MyAutowired註解修飾的物件
                Object o = type.newInstance();
                // 把物件注入到MyAutowired註解修飾的屬性
                field.set(userController, o);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        assertEquals(userController.getUserName(), "abc");
    }
}

參考資料

實現Spring autowired

https://blog.csdn.net/qq_30763385/article/details/108969883