web-dev-qa-db-ja.com

セッターなしの@AutowiredアノテーションによるSpring依存性注入

私は今のところ数か月からSpringを使用しており、@Autowiredアノテーションを使用した依存関係の注入には、フィールドに注入するためのセッターも必要だと思いました。

だから、私はそれを次のように使用しています:

@Controller
public class MyController {

    @Autowired
    MyService injectedService;

    public void setMyService(MyService injectedService) {
        this.injectedService = injectedService;
    }

    ...

}

しかし、私は今日これを試しました:

@Controller
public class MyController {

    @Autowired
    MyService injectedService;

    ...

}

そして驚いたことに、コンパイルエラー、起動時のエラーはなく、アプリケーションは完全に実行されています...

だから私の質問は、@Autowiredアノテーションを使用した依存関係の注入にセッターが必要かどうかです。

Spring 3.1.1を使用しています。

26
Tony

@Autowiredではセッターは必要ありません。値はリフレクションによって設定されます。

完全な説明については、この投稿を確認してください Spring @Autowiredの仕組み

41
Arnaud Gourlay

いいえ、Javaセキュリティポリシーにより、Springがパッケージ保護フィールドのアクセス権を変更することが許可されている場合、セッターは不要です。

4
Boris Pavlović
package com.techighost;

public class Test {

    private Test2 test2;

    public Test() {
        System.out.println("Test constructor called");
    }

    public Test2 getTest2() {
        return test2;
    }
}


package com.techighost;

public class Test2 {

    private int i;

    public Test2() {
        i=5;
        System.out.println("test2 constructor called");
    }

    public int getI() {
        return i;
    }
}


package com.techighost;

import Java.lang.reflect.Field;

public class TestReflection {

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class<?> class1 = Class.forName("com.techighost.Test");
        Object object = class1.newInstance();
        Field[] field = class1.getDeclaredFields();
        field[0].setAccessible(true);
        System.out.println(field[0].getType());
        field[0].set(object,Class.forName(field[0].getType().getName()).newInstance() );
        Test2 test2 = ((Test)object).getTest2();
        System.out.println("i="+test2.getI());

    }
}

これはリフレクションを使用して行われる方法です。

2
Sunny Gupta