在构造函数上使用@Autowired

Har*_*ana 2 java spring

在构造函数上使用@Autowired的好处是什么,如下所示,

@Autowired
public MyClass(A a){
} 
Run Code Online (Sandbox Code Playgroud)

Pre*_*ric 6

这样bean A将被注入构造函数中.它更清晰,因为你可以声明bean的依赖关系,因为它不能在没有提供的情况下实例化A.这使得测试变得更加容易.