2012-04-13 12 views
21

私はSpringを数ヶ月から使用していますが、@Autowiredアノテーションを使った依存性注入には、フィールドを注入する必要があります。Spring依存性注入@Autowired setterなし

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

@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を使用しています。

+3

あなた自身の質問にお答えしたようです。 – darrengorman

答えて

35

@Autowiredを設定する必要はありません。値はリフレクションによって設定されます。完全な説明How does Spring @Autowired work

+0

クイック返信ありがとう! – Tony

+0

リンクされた投稿を忘れないでください;) –

+0

フィールドはプライベートにすることができ、Spring Autowiredはセッターなしでも動作します。 – chalimartines

3

ないため

チェックこの記事を、Javaセキュリティポリシーは、春はセッターが必要とされていないパッケージprotectedフィールドのアクセス権を変更することができます。

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()); 

    } 
} 

これは、それが反射を利用して行う方法です。