我现在使用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。
答案 0 :(得分:38)
您不需要使用@Autowired的setter,该值由反射设置。
查看此帖子以获取完整说明How does Spring @Autowired work
答案 1 :(得分:4)
不,如果Java安全策略允许Spring更改受保护包的字段的访问权限,则不需要setter。
答案 2 :(得分: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());
}
}
这是使用反射完成的方式。