繁体   English   中英

使用@Autowired注释的Spring依赖注入,不带setter

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM