3

Spring の DI をコーディングしようとしていますが、単純な例です。コントローラーがあり、この @AutoWired は私が定義した空の注釈です。

public class UserController {
    @AutoWired
    private UserServise userServise;// a empty interface
}

Annotation インジェクションを実装するコードは次のとおりです。

UserController userController = new UserController();
Class<? extends UserController> clazz = userController.getClass();

Stream.of(clazz.getDeclaredFields()).forEach(field -> {
    AutoWired annotation = field.getAnnotation(AutoWired.class);
    if (annotation != null) {
        field.setAccessible(true);
        Class<?> type = field.getType();
        try {
            Object o = type.getDeclaredConstructor().newInstance();
            field.set(userController, o);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

プログラムが実行されたとき

Object o = type.getDeclaredConstructor().newInstance();

スロー

java.lang.NoSuchMethodException: com.learning.servise.UserServise.<init>()

プログラムはインターフェイスのコンストラクターを見つけることができないと思います。では、インジェクション用にこのインスタンスを作成するにはどうすればよいですか?

4

1 に答える 1