Spring依赖注入@Autowired没有setter

Ton*_*ony 26 java spring dependency-injection autowired

我现在使用Spring几个月了,我认为使用@Autowired注释的依赖注入也需要为该字段注入一个setter.

所以,我这样使用它:

@Controller
public class MyController {

    @Autowired
    MyService injectedService;

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

    ...
Run Code Online (Sandbox Code Playgroud)

}

但我今天试过这个:

@Controller
public class MyController {

    @Autowired
    MyService injectedService;

    ...
Run Code Online (Sandbox Code Playgroud)

}

哦惊喜,没有编译错误,启动时没有错误,应用程序运行完美...

所以我的问题是,使用@Autowired注释进行依赖注入所需的setter是什么?

我正在使用Spring 3.1.1.

Arn*_*lay 41

你不需要带有@Autowired的setter,该值是通过反射设置的.

查看这篇文章以获得完整的解释Spring @Autowired是如何工作的