如果我有 :
@Component
class Foo {
@Autowired
private Bar b; //where b is @Service
public Foo(){
//if i need to use b here, what do i need to do?
b.something(); // <-- b is null so it'll crash here
}
public void setB(Bar b){
this.b = b;
}
}
通过阅读 Spring 文档,我了解到基于 setter 的注入方法比基于构造函数的注入更推荐,但在上面的示例中,我需要在当前类的构造函数中使用注入的 spring 类,以便它必须是基于构造函数的注入正确吗?
如果是这样,它会是什么样子?
@Component
class Foo {
private Bar b; //where b is @Service
@Autowired
public Foo(Bar b){
b.something(); // b won't be null now !
}
}