![](/img/trans.png)
[英]Spring dependency injection @Autowired VS dependency injection of an object without @Autowired
[英]Spring dependency injection with @Autowired annotation without setter
我現在使用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
注釋進行依賴注入所需的setter是什么?
我正在使用Spring 3.1.1。
你不需要帶有@Autowired的setter,該值是通過反射設置的。
查看這篇文章以獲得完整的解釋Spring @Autowired是如何工作的
不,如果Java安全策略允許Spring更改受保護包的字段的訪問權限,則不需要setter。
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());
}
}
這是使用反射完成的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.