Java 带有@Autowired注释的Spring依赖项注入,不带setter
几个月以来我一直在使用Spring,我认为带有Java 带有@Autowired注释的Spring依赖项注入,不带setter,java,spring,dependency-injection,autowired,Java,Spring,Dependency Injection,Autowired,几个月以来我一直在使用Spring,我认为带有@Autowired注释的依赖项注入也需要为字段注入setter 所以,我是这样使用它的: @Controller public class MyController { @Autowired MyService injectedService; public void setMyService(MyService injectedService) { this.injectedService = inje
@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,该值由反射设置
查看此帖子以获得完整的解释否,如果Java安全策略允许Spring更改包保护字段的访问权限,则不需要设置程序。
package com.techighost;
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());
}
}
公开课考试{
私有Test2 Test2;
公开考试(){
System.out.println(“调用的测试构造函数”);
}
公共测试2 getTest2(){
返回test2;
}
}
package com.techighost;
公共类Test2{
私人互联网i;
公共测试2(){
i=5;
System.out.println(“调用了test2构造函数”);
}
公共int getI(){
返回i;
}
}
package com.techighost;
导入java.lang.reflect.Field;
公共类测试反射{
publicstaticvoidmain(字符串[]args)抛出ClassNotFoundException、InstantiationException、IllegalAccessException{
Class class1=Class.forName(“com.techighost.Test”);
Object Object=class1.newInstance();
Field[]Field=class1.getDeclaredFields();
字段[0]。setAccessible(true);
System.out.println(字段[0].getType());
字段[0].set(对象,类.forName(字段[0].getType().getName()).newInstance());
Test2 Test2=((测试)对象).getTest2();
System.out.println(“i=“+test2.getI());
}
}
这是如何使用反射完成的。似乎您已经回答了自己的问题。别忘了打开链接帖子;)字段可以是私有的,Spring Autowired也可以在没有setter的情况下工作。