2012-04-13 165 views
21

我現在正在使用Spring,因爲幾個月後,我認爲使用@Autowired註釋進行依賴注入也需要一個setter來注入該字段。Spring依賴注入@Autowired without setter

所以,我使用它是這樣的:

@Controller 
public class MyController { 

    @Autowired 
    MyService injectedService; 

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

    ... 

}

但我已經試過這今天:

@Controller 
public class MyController { 

    @Autowired 
    MyService injectedService; 

    ... 

}

噢驚喜,沒有編譯錯誤,啓動時無錯誤,應用程序運行完美...

所以我的問題是,使用@Autowired註釋進行依賴注入需要setter嗎?

我使用Spring 3.1.1。

+3

似乎你已經回答了你自己的問題。 – darrengorman 2012-04-13 13:02:10

回答

35

您不需要帶@Autowired的setter,該值由反射設置。

檢查這個職位完整說明How does Spring @Autowired work

+0

感謝您的快速回復! – Tony 2012-04-13 13:02:54

+0

不要忘記鏈接的文章;) – 2012-04-13 13:05:23

+0

字段可以是私人的,Spring Autowired也可以不使用setter。 – chalimartines 2012-04-13 13:17:44

3

不,如果Java安全策略允許Spring更改不需要二傳手包保護字段的訪問權限。

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

    } 
} 

這是如何使用反射完成的。