27

私は今のところ数か月から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アノテーション付きの依存性注入にセッターが必要ですか?

Spring3.1.1を使用しています。

4

3 に答える 3

42

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

完全な説明については、この投稿を確認してくださいSpring@Autowiredはどのように機能しますか

于 2012-04-13T13:00:05.960 に答える
4

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

于 2012-04-13T13:01:17.003 に答える
2
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());

    }
}

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

于 2013-07-07T10:03:14.550 に答える